MySQL 获取具有特定属性的项目,按包含的属性数排序

MySQL get items with specific attributes ordered by number of attributes contained

我有 3 个表: 食物-

id    name
1     pizza
2     pasta
3     salad

标签

id    tagName
1     spicy
2     non-spicy
3     healthy
4     cheesy

food_tag

id    food_id    tag_id
1     1          1
2     1          4
3     2          2
4     2          4
5     3          3
6     3          2

我想查询这三个表以获取按最大匹配标签数排序的食品。因此,如果我查询带有标签 ('spicy'、'cheesy') 的食物,我应该按此顺序获取 Pizza 和 Pasta,但不是沙拉(因为它不包含任何相关标签)。

我正在尝试这个查询,它没有给我想要的结果:

SELECT a.name, COUNT(DISTINCT c.tagName) FROM food a, tags b, food_tag c
 WHERE b.tagName in ('spicy', 'cheesy') AND b.id = c.tag_id 
 AND a.id = c.food_id ORDER BY COUNT(DISTINCT c.tagName) DESC;

我想要的输出是:

a.name   count(distinct c.tagName)  
pizza    2
pasta    1

谁能告诉我我的错误是什么?

问题

  • missing group by a.name

调整后的查询

SELECT a.name, COUNT(DISTINCT b.tagName) 
FROM food a, tags b, food_tag c 
WHERE b.tagName in ('spicy', 'cheesy') 
AND b.id = c.tag_id 
AND a.id = c.food_id 
group by a.name
ORDER BY COUNT(DISTINCT b.tagName) DESC
;

输出

+-------+---------------------------+
| name  | COUNT(DISTINCT b.tagName) |
+-------+---------------------------+
| pizza |                         2 |
| pasta |                         1 |
+-------+---------------------------+

sqlfiddle