0

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

  • 项目 - ID 和其他一些
  • 标签 - ID 和名称
  • item_tags - 带有 IDitem 和 IDtag 的联结表

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

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";

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

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

4

2 回答 2

1

well you know your list, so that is a simple string. and you know your count. these can be jammed into a mysql Prepared Statement and executed.

But below it is with the list and count plopped in just for demo purposes.

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)
于 2015-07-16T17:13:22.223 回答
0

只需使用 . 查找与两个标签匹配的所有内容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"
);
于 2015-07-16T17:03:30.480 回答