2014-10-07 65 views
0
选择不同的酒吧foo的

比方说,我有两个表:从2个表

Table foo 
=========== 
id | val 
-------- 
01 | 'a' 
02 | 'b' 
03 | 'c' 
04 | 'a' 
05 | 'b' 

Table bar 
============ 
id | class 
------------- 
01 | 'classH' 
02 | 'classI' 
03 | 'classJ' 
04 | 'classK' 
05 | 'classI' 

我想返回FOO的所有值和酒吧,是其中富在多个不同的酒吧存在。因此,在此示例中,我们将返回:

val | class 
------------- 
'a' | 'classH' 
'a' | 'classK' 

因为尽管'b'也存在多次,它也具有相同的bar值。

我有以下查询返回的其中有多个酒吧都富,就算了吧是相同的:

select distinct foo.val, bar.class 
from foo, bar 
where foo.id = bar.id 
and 
(
    select count(*) from 
    foo2, bar2 
    where foo2.id = bar2.id 
    and foo2.val = foo.val 
) > 1 
order by 
va.name; 

回答

2
select f.val, b.class 
from foo f 
join bar b on f.id = b.id 
where f.val in (
    select f.val 
    from foo f 
    join bar b on f.id = b.id 
    group by f.val 
    having count(distinct b.class) > 1 
); 
+0

尼斯查询+1从我:) – 2014-10-07 18:40:14

+0

简单,我需要什么。顺便说一下,我正在学习一门SQL课程,而我们的老师可以提出疑问,但他们通常需要深入3到4个子查询并且有很多过剩......您是否使用过任何优秀的材料来编写查询? – ironicaldiction 2014-10-07 19:55:47

+0

@ironicaldiction抱歉,没有任何建议。我通常在网上搜索(通常最终在这里) – FuzzyTree 2014-10-07 22:14:46

1

你可以使用具有全部重复,以显示每个子查询使用EXISTS行像这样。

SELECT f.val, b.class 
FROM foo f 
JOIN bar b ON b.id = f.id 
WHERE EXISTS 
( SELECT 1 
    FROM foo 
    JOIN bar ON foo.id = bar.id 
    WHERE foo.val = f.val 
    GROUP BY foo.val 
    HAVING COUNT(DISTINCT bar.class) > 1 
); 

Fiddle Demo

普遍存在执行比这就是为什么我喜欢它了...更多细节关于VS存在MY POST HERE

1

你可以做一个子查询,以获得更快的人口从符合条件(名称)的foo开始。然后加入回两个表,以获得您想要的信息输出:

select f.val, b.class 
from (select f.val 
     from foo f join 
      bar b 
      on f.id = b.id 
     group by f.val 
     having count(distinct b.class) > 1 
    ) bf join 
    foo f 
    on bf.val = f.val join 
    bar b 
    on f.id = b.id 
1
select f.val, b.class 
    from foo f 
    join bar b 
    on f.id = b.id 
    join (select f.val 
      from foo f 
      join bar b 
      on f.id = b.id 
     group by f.val 
     having count(distinct b.class) > 1) v 
    on b.val = v.val