查询IN匹配所有

时间:2012-09-18 11:21:21

标签: sql database

我有两张桌子

Report
----------
report_id
name

Template
------------
template_id
report_id

报告可以包含许多模板。如何查询以获取具有与项目列表匹配的模板的报告

例如,如果模板有这些行

Template_ID  | Report_ID
---------------------------
a              1
b              1
c              2
d              3 

选择报告时,我需要确保表中的所有模板都符合文件管理器条件,过滤条件中是否有不在数据库中的附加项无关紧要。

实施例

查找模板a,b,c的所有报告。 这将返回报告1,因为a,ba,b,c的子集,也是报告2,因为ca,b,c

的子集

查找模板a的所有报告 - 这不会有行。因为没有报告只有a模板

查找模板c的所有报告 - 这只会返回报告2.

查找模板c,d的所有报告 - 这只返回报告2和3,因为cc,d的子集,而d也是c,d的子集1}}。

查找模板d,e的所有报告 - 这只会返回报告3,因为dc,e

的子集

5 个答案:

答案 0 :(得分:2)

这是SQLFiddle demo

select distinct Report_id 
   from Template T
   where Template_id in ('d','e')
   and NOT EXISTS 
      (select T1.Report_id 
        from Template T1
        where Template_id not in ('d','e')
        and T.Report_id=T1.Report_id)

答案 1 :(得分:1)

使用您的集合中的模板查找所有报告;使用不在您的集合中的模板从所有报告中减去。

答案 2 :(得分:1)

此查询返回2,我认为该描述是正确的:

SELECT DISTINCT t1.report_id
  FROM template t1
  LEFT JOIN (
    SELECT *
      FROM template
      WHERE template_id NOT IN ('b', 'c')
  ) t2 ON t1.report_id = t2.report_id
  WHERE t1.template_id IN ('b', 'c')
    AND t2.template_id IS NULL

编辑:这基本上是斯科特的答案,但我没有看到它。遗憾。

答案 3 :(得分:1)

这是一种不同的方法。我喜欢这个,因为你不需要复制模板列表:

SELECT t1.report_id
  FROM (
    SELECT report_id, COUNT(*) AS report_count
      FROM template
      GROUP BY report_id
  ) t1
  INNER JOIN (
    SELECT report_id, COUNT(*) AS report_count
      FROM template
      WHERE template_id IN ('b', 'c')
      GROUP BY report_id
  ) t2 ON t1.report_id = t2.report_id
  WHERE t1.report_count = t2.report_count

答案 4 :(得分:0)

select distinct report_id from template where template_id in (<list>)
minus
select distinct report_id from template where template_id not in (<list>)
相关问题