php - MySQL 查询帮助 - 将标签功能转换为 SQL 数据库

标签 php mysql sql mysqli

我目前正在尝试将网站的功能从使用 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/

相关文章:

php - 如何在MySQL中选择所有类别并统计每个类别文章的数量

sql - 查找表中值的最长序列

sql - 在 SELECT 结果上使用 IN 运算符的 IF 语句

php - 如何在 PHP 中使用正则表达式匹配空格、回车和换行?

php - Codeigniter - 将三个表组合成正确的 View 格式

php - 从 mysql 回显更多行

mysql - MySQL UNION 多个表,但只返回 1 个结果,为什么?

mysql - 从一个表中选择多行合并为一行

PHP - RSS 生成器

php - mysql 到服务器的链接丢失,无法重新连接