2013-06-24 35 views
3

给定一个表定义的所有相关的选项:SQL查询:选择行,如果有相关表中

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 

的问题是如何来选择既科学所有文章?

请注意,它应该是一般的[第2..N)标签的组合...

感谢您的帮助。

+1

请与一个特定的更换你的** **的SQL标签到您正在使用的RDBMS(MySQL,SQL-Server,Oracle等)。最好的答案取决于你使用的是哪个版本。 – Barmar

+0

[选择至少包含一个功能列表的所有行]的可能重复(http://stackoverflow.com/questions/13889547/select-all-rows-that-have-at-least-a-list-of-特征) – Barmar

回答

3

您可以使用下面的查询得到的结果:

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 

SQL Fiddle with Demo

或者这可以写成:

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) >= ; 

SQL Fiddle with Demo

如果你只是想要回文章编号,那么你可以只查询article_tag表:

select art_id 
from article_tags 
where tag_id in (1, 3) 
group by art_id 
having count(distinct tag_id) = 2 

SQL Fiddle with Demo

1
SELECT * 
FROM  articles 
WHERE  art_id IN 
      (
       SELECT art_id 
       FROM  article_tags 
       GROUP BY art_id 
       HAVING COUNT(art_id) > 1 
     )