简体   繁体   English

如何在MySQL中选择与其他表中的多行相交的行?

[英]Howto Select rows that match the intersection of multiple rows in other tables in MYSQL?

It seems complicated (and probably it is). 似乎很复杂(可能是这样)。 But i cant imagine how to solve this. 但是我无法想象如何解决这个问题。

There are tables: 有表:

COMPANIES 公司介绍
id | id | name 名称
1 | 1 | Google 谷歌
2 | 2 | Samsung 三星
3 | 3 | Microsoft 微软

PARAGRAPHS 段落
id | id | name 名称
1 | 1 | Header 标头
2 | 2 | Body 身体
3 | 3 | Footer 页脚

TAGS 标签
id | id | tag 标签
1 | 1 | Internet 互联网
2 | 2 | Softwate 软绵绵的

COMPANIES_VS_TAGS COMPANIES_VS_TAGS
id | id | company_id | company_id | tag_id tag_id
1 | 1 | 1 | 1 | 1 1个
2 | 2 | 2 | 2 | 2 2
3 | 3 | 3 | 3 | 1 1个
4 | 4 | 3 | 3 | 2 2

PARAGRAPHS_VS_TAGS PARAGRAPHS_VS_TAGS
id | id | paragraph_id | 段落编号| tag_id tag_id
1 | 1 | 2 | 2 | 1 1个
1 | 1 | 2 | 2 | 2 2

I need to select all companies, that belongs to [any_number] of tags that belongs to paragraph by logical AND . 我需要通过逻辑AND选择属于属于段落的标签的[any_number]个公司。

So, in the example above, the Body paragraph should output the only company "Microsoft". 因此,在上面的示例中,“正文”段应输出唯一的公司“ Microsoft”。

ADD: I can use only WHERE and SubQueries : this is the limitation of CMS i have to use. 添加:我只能使用WHERE和SubQueries :这是我必须使用的CMS的限制。

You just need to join all your tables: 您只需要加入所有表:

SELECT companies.id, 
       companies.name 
FROM   companies, 
       tags, 
       companies_vs_tags, 
       paragraphs_vs_tags 
WHERE  companies.id = companies_vs_tags.company_id 
       AND tags.id = companies_vs_tags.tag_id 
       AND tags.id = paragraphs_vs_tags.tag_id 
       AND paragraphs.id = paragraphs_vs_tags.paragraph_id 
       AND paragraphs.name = "Microsoft"; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM