4

给定一个表定义:

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) 标签组合,它应该是通用的...

谢谢您的帮助。

4

2 回答 2

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

或者可以这样写:

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

如果您只想返回文章 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

请参阅带有演示的 SQL Fiddle

于 2013-06-24T15:06:22.893 回答
1
SELECT    * 
FROM      articles 
WHERE     art_id IN 
          (
               SELECT    art_id 
               FROM      article_tags 
               GROUP BY  art_id 
               HAVING    COUNT(art_id) > 1
          ) 
于 2013-06-24T15:11:20.257 回答