MySQL - select 具有多个主题标签的所有项目

MySQL - select all items with multiple hashtags

我正在为我的网页制作主题标签系统,并且有三个 table:

选择具有给定主题标签的所有项目非常简单:

SELECT items.* FROM items
join item_tags on items.ID=item_tags.IDitem
join tags on item_tags.IDtag=tags.ID
where tags.name="something";

问题是,如果我想 select 所有带有多个标签的项目,例如,找到所有标记为猫和动物的项目,我该怎么办?

我考虑过制作临时 table,插入所有带有第一个标签的项目,然后留下带有第二个标签的项目,然后是第三个,然后是第四个等等,但它看起来不太好而且太快了。

只需使用 IN 找到所有与这两个标签匹配的内容。像这样:

SELECT DISTINCT items.* FROM items 
INNER JOIN item_tags on items.ID=item_tags.IDitem 
INNER JOIN tags on item_tags.IDtag=tags.ID 
WHERE tags.name="something"
AND items.* IN (
    SELECT items.* FROM items 
    INNER JOIN item_tags on items.ID=item_tags.IDitem 
    INNER JOIN tags on item_tags.IDtag=tags.ID 
    WHERE tags.name="somethingelse"
);

你知道你的列表,所以这是一个简单的字符串。你知道你的计数。这些可以塞进 mysql Prepared Statement 并执行。

但下面是列表和计数,只是为了演示目的。

create table items
(   id int not null
);

create table tags
(   id int not null,
    name varchar(50)
);

create table item_tags
(   iid int not null,
    tid int not null
);

insert items (id) values (1),(2),(3),(4);
insert tags(id,name) values (1,'cat'),(2,'animal'),(3,'has nose');
-- note, everything has a nose so far:
insert item_tags (iid,tid) values (1,1),(1,3),(2,1),(2,3),(3,2),(3,3),(4,1),(4,2),(4,3);

select i.id,count(i.id)
from items i
join item_tags junc
on junc.iid=i.id
join tags t
on t.id=junc.tid and t.name in ('cat','animal')
group by i.id
having count(i.id)=2

-- only item 4 has both cat and animal (note nose is irrelevant)