我目前正在尝试将网站的功能从使用 php 和文本文件转换为使用 MySQL 数据库。我已经设置了数据库并填写了表格。
数据库包含以下内容:
Table: Items
Columns: Item_ID, Item_Name
Table: Tags
Columns: Tag_ID, Tag_Name
Table: Items_Tags
Columns: Item_ID, Tag_ID
如何创建以下查询?
1) 返回与名为“x”的项目具有 4 个或更多相同标签的所有项目的名称。
For example, say an item x has tags a,b,c,d,e,f and item y has tags a,b,c,d then i need to return y and others that have at least 4 of the same tags as x
2) 返回 2 个项目共有的标签名称
Expanding on the one above, using x and y, return a,b,c,d since they have those in common
3) 返回具有以下标签“a”、“b”、“c”的项目的名称
x and y would be returned because they have a,b,c as tags
到目前为止我的尝试
因关系不密切而被删除
最佳答案
使用GROUP BY
select i.Item_Name,
count(distinct t.Tag_Name) as tag_count
from Items i join Items_Tags it on i.Item_ID = it.Item_ID
join Tags t on it.Tag_ID = t.Tag_ID
where i.Item_Name = 'X'
group by i.Item_ID
having count(distinct t.Tag_Name) >= 4;
关于php - MySQL 查询帮助 - 将标签功能转换为 SQL 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34764596/