2012-09-18 112 views
1

比赛我有两个表查询在所有

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的子集。

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

+0

'c'也是'a,b,c'的一个子集,为什么你的第一个例子不会返回报告2 ? – lanzz

+0

当然报告“a,b,c”应该报告1和2?以及只有报告1,肯定会返回报告1? – BugFinder

+0

@lanzz对不起,你是正确的,我会更新我的错误。BugFinder辜负你的名字我看到=) – Daveo

回答

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) 
+0

真棒从来不知道SQLFiddle存在,你的代码工作得很好 – Daveo

1

一个子集,找到所有的在你的一套模板的报告;从所有报告中减去一个不在你的集合中的模板。

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 

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

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>) 
+0

谢谢,但未能得到这个工作零下似乎是Oracle或DB特定的命令,而不是标准 – Daveo

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 
+0

感谢您的兼具优良他们似乎答案很好地工作,我可以仅仅通过VALEX复制并粘贴到SQLFiddle,他们只是工作!希望我可以选择更多的正确答案。与Valex一起看执行计划,看起来他的表现会更快? – Daveo

+0

剖析会是最好的,但做不到这一点那么这将是合理的考虑执行计划。 – Neil