0

这是交易 - 我在这里有三张桌子:

Companies:
ID | NAME | DETAILS

TAGS
ID | TAGNAME

TAGS_COMPANIES
COMPANY_ID | TAGID

使用嵌套查询,我可以检索由某个集合中的标签标记的所有公司,即:

select c.* from companies c where c.id in (select t.company_id where t.tagid in (12,43,67))

上面的查询返回标签 id 为 12、43 或 67 的所有公司,但我需要检索所有标签为 12 AND 43 AND 67 的公司

我将如何在这里重做我的查询?我正在使用 MySQL

4

2 回答 2

1

效率不高但有效:

select c.* 
from companies c 
where c.id in (select t.company_id from tags_companies t where t.tagid = 12)
and c.id in (select t.company_id from tags_companies t where t.tagid = 43)
and c.id in (select t.company_id from tags_companies t where t.tagid = 67)

使用 HAVING 子句的另一种可能性:

select c.id, c.name, c.details
from companies c join tags_companies t on c.id = t.company_id
where t.tagid in (12, 43, 67)
group by c.id, c.name, c.details
having count(distinct t.tagid) = 3
于 2011-04-12T08:19:26.770 回答
0

有一个子查询。

select c.* 
      from companies c  
      where (c.id, 3) in 
         (select t.company_id, count(distinct t.tagid) 
                 from tags t
           where t.tagid in (12,43,67) 
             group by t.company_id)

幻数 3 表示不同的标签计数。

于 2011-04-12T08:29:00.793 回答