MYSQL按出现次数排序

时间:2017-12-11 23:51:56

标签: mysql

我有像这样的数据库

ID    DESCRIPTION
1     potato tomato
2     potato
3     salad coffee
4     potato salad
5     coffee

如果我搜索“马铃薯”和“沙拉”字样,结果必须

ID    RESULT
4     2
3     1
2     1
1     1

我在php中做过这个,但是根据要搜索的单词数量有很多查询,我认为这不好......

有可能只在mysql中创建吗?

1 个答案:

答案 0 :(得分:1)

尝试以下

CREATE TABLE products(
  ID int,
  DESCRIPTION varchar(20)
);

INSERT products (ID,DESCRIPTION) VALUES
(1,'potato tomato'),
(2,'potato'),
(3,'salad coffee'),
(4,'potato salad'),
(5,'coffee');

SELECT
    p.ID,
    p.DESCRIPTION,
    COUNT(w.word) word_count,
    GROUP_CONCAT(w.word) words
FROM products p
JOIN
    (
        SELECT 'potato' word
        UNION ALL SELECT 'salad'
    ) w
ON p.DESCRIPTION LIKE CONCAT('%',w.word,'%')
GROUP BY p.ID,p.DESCRIPTION
ORDER BY word_count DESC