2013-06-24 59 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 
     )