2011-02-14 59 views
0

我需要帮助简化下面的查询。用相关子查询简化查询以简化连接

我能够检查'0'计数,但没有在下面的查询中使用Group By/having子句,但是与相关子查询有关。

现在,我被要求将下面的查询简化为简单的连接!

我尝试将查询合并为一个。但产量不同。

您能否提出任何简化查询的其他想法,即检查'0'计数。

select distinct tab1.col1 
    from tab1 
    where tab1.col2 = 'A' 
    And 0 = (select count(tab2.col1) 
      from tab2 
      where tab2.col2 = 'B' 
      and tab2.col1 = tab1.col1) 

回答

3

这种事情通常会被写成一个NOT EXISTS

SELECT distinct tab1.col1 
    FROM tab1 
WHERE tab1.col2 = 'A' 
    AND NOT EXISTS( 
     SELECT 1 
     FROM tab2 
     WHERE tab2.col2 = 'B' 
     AND tab2.col1 = tab1.col1) 

然而,你也可以写

SELECT tab1.col1, count(tab2.col1) 
    FROM (SELECT * FROM tab1 WHERE col2 = 'A') tab1, 
     (SELECT * FROM tab2 WHERE col2 = 'B') tab2 
WHERE tab1.col1 = tab2.col2(+) 
GROUP BY tab1.col1 
HAVING count(tab2.col1) = 0 
+0

非常感谢你Justin .... :)感谢U太Ronnis .. :) – Savitha 2011-02-14 08:17:26

3

尝试其中的一些。 如果col1被声明为非空,则前两个查询具有相同的执行计划(反连接)。第二种选择是我的个人建议,因为它最符合您的要求。

-- Non-correlated subquery 
select distinct col1 
    from tab1 
where col2 = 'A' 
    and col1 not in(select col1 
        from tab2 
        where col2 = 'B'); 

-- Correlated subquery 
select distinct col1 
    from tab1 
where col2 = 'A' 
    and not exists(select 'x' 
        from tab2 
        where tab2.col2 = 'B' 
        and tab2.col1 = tab1.col1); 

-- Using join 
select distinct tab1.col1 
    from tab1 
    left join tab2 on(tab2.col2 = 'B' and tab2.col1 = tab1.col1) 
where tab1.col2 = 'A' 
    and tab2.col1 is null; 

-- Using aggregation 
select tab1.col1 
    from tab1 
    left join tab2 on(tab2.col2 = 'B' and tab2.col1 = tab1.col1) 
where tab1.col2 = 'A' 
group 
    by tab1.col1 
having count(tab2.col2) = 0;