使用SQL搜索字符串中最常出现的值

使用SQL搜索字符串中最常出现的值,sql,string,count,sql-order-by,Sql,String,Count,Sql Order By,如果你有一个字符串,比如: "lorum ipsum testing with some dummy text lorum woop what testing again." 您有一个数据库表,如: ID | TESTING --------------- 1 | dummy 2 | lorum 3 | trol 4 | haha 如何仅使用sql检查字符串中出现最多的值 因此,在本例中,它将返回:2 | lorum 起初我认为LOCATE()函数会很有用。例如,

如果你有一个字符串,比如:

"lorum ipsum testing with some dummy text lorum woop what testing again."
您有一个数据库表,如:

ID |   TESTING
---------------
1  |   dummy
2  |   lorum
3  |   trol
4  |   haha
如何仅使用sql检查字符串中出现最多的值

因此,在本例中,它将返回:
2 | lorum

起初我认为
LOCATE()
函数会很有用。例如,我试过:

SELECT *, LOCATE(testing, "<<string comes here>>") FROM <table>
选择*,从

这可能吗?如果不是,最好的方法是什么

这很痛苦,但您可以使用
之类的
和一些字符串操作来计算字符串中的匹配数:

select t.testing,
       (length(v.str) - length(replace(v.str, t.testing, ''))) / length(t.testing) as num_times 
from (values ('lorum ipsum testing with some dummy text lorum woop what testing again.')
     ) v(str) join
     t
     on str like concat('%', t.testing, '%')
order by num_times desc
limit 1;

注意:这是通用的。在Postgres中,我会将字符串拆分为单词并进行相等比较。

对于Postgres,这非常简单:

select word, count(*)
from regexp_split_to_table('lorum ipsum testing with some dummy text lorum woop what testing again.', '\s') as x(word)
group by word
order by count(*) desc
下面是一种方法(在Ms SQL中实现),它利用
STRING\u SPLIT(,)
将测试字符串转换为表。该表可以与字典联接,所有匹配项都可以使用GROUPBY进行计数。 我打电话给字典表
dictionary

SELECT sub.testing, COUNT(sub.testing) FROM 
(   SELECT d.testing FROM DICTIONARY d
    INNER JOIN ( SELECT value FROM STRING_SPLIT('lorum ipsum testing with some dummy text lorum woop what testing again.', ' ') ) s
    ON d.testing = s.value
)   sub
GROUP BY sub.testing
ORDER BY COUNT(sub.testing) DESC
结果:字典表中的所有匹配值都将以降序列出计数,在Oracle中,您可以使用,从版本11g开始提供:

select *
from mytable
order by regexp_count(
    'lorum ipsum testing with some dummy text lorum woop what testing again.',
    '(^|\W)' || testing || '(\W|$)'
) desc
fetch first 1 rows only

ID | TESTING -: | :------ 2 | lorum

我删除了不一致的数据库标记。请只标记您实际使用的数据库。当然@GordonLinoff,我只是还没有为我的项目选择数据库,并且正在考虑其中任何一个。下次如果我不确定的话,我就不包括它们了。谢谢
select id, testing, count(m)
from 
    mytable t,
    regexp_matches(
        'lorum ipsum testing with some dummy text lorum woop what testing again.', 
        '\y' || t.testing || '\y',
        'g'
    ) m
group by id, testing
order by count(m)::int desc
limit 1