Mysql - 选择,按字符串中出现列值的顺序排序

时间:2009-12-12 14:32:13

标签: mysql select

对不起,我应该更好地解释一下:我有一个$ string,我希望'table'按'word'列下每个值出现在$ string中的顺序排序。 因为我需要一个像这样的查询:

'SELECT * FROM table WHERE $string 
LIKE CONCAT("%",LOWER(word),"%")...

找到单词,然后我想通过外观来命令它们:

$string = "lollipop lollipop oh la le la le lollipop";
'SELECT * FROM table'
++++++++++table++++++++++
id - word
1  - la
2  - le
3  - lollipop
4  - shooby
+++++++++++++++++++++++++

(对表的一些查询)将输出:

++++++++++table++++++++++
id - word
1  - lollipop (appears 3 times)
2  - le (appears 2 times)
3  - la (appears 2 times)
4  - shooby (appears 0 times)
+++++++++++++++++++++++++

执行此操作的查询是什么? (顺便说一句,如果字符串中出现的每个单词的次数也会显示在选择表中,那就太好了。)

2 个答案:

答案 0 :(得分:2)

您可以使用的一个技巧是替换原始字符串中的单词。然后比较丢失的字符数。除以单词的长度,这将为您提供该单词的总出现次数。例如:

SELECT 
    w.word
,   (length(title) - length(replace(title, w.word, ''))) / length(word)
FROM (select 'lollipop lollipop oh la le la le lollipop' as title) t
CROSS JOIN (
    select 'la' as word
    union all select 'le'
    union all select 'lollipop'
    union all select 'shooby'
) w

-->

la          2.0000
le          2.0000
lollipop    3.0000
shooby      0.0000

答案 1 :(得分:0)

如果我按照你的要求行事......

SELECT word, word_count
  FROM
  (SELECT word, COUNT(word) `word_count` FROM table GROUP BY word) order_table
  ORDER BY word_count DESC