SQL 问题 - 如何选择包含第二个表中所有引用的所有元组?

发布于 2024-10-31 17:38:17 字数 396 浏览 1 评论 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

Heres the deal - I have three tables here:

Companies:
ID | NAME | DETAILS

TAGS
ID | TAGNAME

TAGS_COMPANIES
COMPANY_ID | TAGID

Using a nested query I can retrieve all companies that are tagged by tags in a certain set i.e:

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

The above query returns all companies that have an either tag id 12, 43 or 67 but I need to retrieve all companies who are tagged 12 AND 43 AND 67

How would I redo my query here? I'm using MySQL

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

通知家属抬走 2024-11-07 17:38:17

不太高效但有效:

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

Not too efficient but works:

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)

Another possibility using a HAVING clause:

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
感情废物 2024-11-07 17:38:17

带有一个子查询。

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 表示不同的标签计数。

With one subquery.

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)

magic number 3 means different tags count.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文