Mysql SQL问题-如何选择包含第二个表中所有引用的所有元组?
交易如下-我这里有三张桌子:Mysql SQL问题-如何选择包含第二个表中所有引用的所有元组?,mysql,sql,sql-optimization,Mysql,Sql,Sql Optimization,交易如下-我这里有三张桌子: 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的所有公
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、43和67的所有公司
我将如何在这里重做我的查询?我使用的是MySQL,效率不太高,但很有效:
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
有一个子查询
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表示不同的标签计数