[英]SQL Query : Selecting a row if it has all related options in a related table
given a table definition: 给定一个表定义:
Articles:
art_id | name
-------|--------------
1 | article1
2 | article2
3 | article3
Tags:
tag_id | description
-------|--------------
1 | Scientific
2 | Long
3 | Short
article_tags:
art_id | tag_id
-------|---------
1 | 1
1 | 2
2 | 1
2 | 3
3 | 1
3 | 2
3 | 3
The question is How to select all articles that are BOTH Scientific and Short ? 问题是如何选择所有科学和短期的文章 ?
Please note, it should be general for [2..N) tag combinations... 请注意,它应该是[2..N]标签组合的一般...
thanks for the help. 谢谢您的帮助。
You can use the following query to get the result: 您可以使用以下查询来获取结果:
select a.art_id, a.name
from articles a
inner join article_tags at
on a.art_id = at.art_id
inner join tags t
on at.tag_id = t.tag_id
where t.description in ('Short', 'Scientific') -- tags here
group by a.art_id, a.name
having count(distinct t.tag_id) = 2 -- total count of tags here
See SQL Fiddle with Demo 请参阅SQL Fiddle with Demo
Or this could be written: 或者这可以写成:
select a.art_id, a.name
from articles a
inner join article_tags at
on a.art_id = at.art_id
inner join tags t
on at.tag_id = t.tag_id
group by a.art_id, a.name
having
sum(case when t.description = 'Short' then 1 else 0 end) >= 1 and
sum(case when t.description = 'Scientific' then 1 else 0 end) >= ;
See SQL Fiddle with Demo . 请参阅SQL Fiddle with Demo 。
If you just want to return the article id, then you could just query the article_tag
table: 如果您只想返回文章ID,那么您只需查询article_tag
表:
select art_id
from article_tags
where tag_id in (1, 3)
group by art_id
having count(distinct tag_id) = 2
SELECT *
FROM articles
WHERE art_id IN
(
SELECT art_id
FROM article_tags
GROUP BY art_id
HAVING COUNT(art_id) > 1
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.