【问题标题】:MySQL - select all items with multiple hashtagsMySQL - 选择具有多个主题标签的所有项目
【发布时间】:2015-10-06 06:05:04
【问题描述】:

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

  • 项目 - 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";

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

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

【问题讨论】:

  • where tags.name in ('apple', 'banana', 'stealth bomber')
  • @MarcB 关闭,但不完全是 - 它选择了所有苹果、所有香蕉和所有隐形轰炸机,但我想要同时是苹果、香蕉和隐形轰炸机的东西。
  • 知道了,那么你需要count(*) as found_tagshaving found_tags = 3
  • @MarcB found_tags 得到很大的值(看起来它计算了所有标签或其他东西)。德鲁皮尔斯的回答也计算了行数,所以我猜你的意思是这样的。

标签: php mysql hashtag junction-table


【解决方案1】:

你知道你的列表,所以这是一个简单的字符串。你知道你的计数。这些可以塞进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)

【讨论】:

  • 工作正常,看起来很容易扩展,所有这一切都在一个查询中(没有嵌套选择的奖励点)。谢谢。
【解决方案2】:

使用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"
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多