更正Oracle查询

时间:2014-01-16 08:18:39

标签: sql database oracle

我的表A有以下记录:

表A

+----+-----+
|Tuid|Etuid|
+----+-----+
|d1  |E1   |
+----+-----+
|d2  |E1   |
+----+-----+
|d3  |E2   |
+----+-----+
|d4  |E3   |
+----+-----+
|d5  |E4   |
+----+-----+

表B

+----+---+
|Tuid|FID|
+----+---+
|d1  |1  |
+----+---+
|d2  |2  |
+----+---+
|d3  |1  |
+----+---+
|d3  |2  |
+----+---+
|d4  |1  |
+----+---+
|d4  |2  |
+----+---+
|d5  |1  |
+----+---+
|d5  |3  |
+----+---+

这里表A和表B的Tuid是相关的。我想在同一个Etuid中查询所有具有1和2个FID的记录。我期待结果是E1,E2和E3。我不应该得到E4,因为它只包含'1'FID而不是'2'。

我写了这样的查询:

SELECT TableA.ETuid
FROM TableA 
WHERE TableA.Tuid IN (
    SELECT TableB.Tuid
    FROM TableB
    WHERE TableB.FID IN (1, 2)
    GROUP BY TableB.Tuid
    HAVING COUNT(*) = 2
)

这只是给出了E2和E3的结果,请帮我在结果中获得E1。

4 个答案:

答案 0 :(得分:1)

这可能不是一个优雅的解决方案,但逻辑非常简单:

SELECT a1.Etuid
  FROM TableA a1
  INNER JOIN TableB b1 ON (a1.Tuid=b1.Tuid)
  WHERE b1.FID=1
INTERSECT
SELECT a2.Etuid
  FROM TableA a2
  INNER JOIN TableB b2 ON (a2.Tuid=b2.Tuid)
  WHERE b2.FID=2;

输出

ETUID
E1
E2
E3

Online demo
(请注意,由于SQLFiddle的约定和我的懒惰,我必须对列名使用双引号;在您的实际代码中可能不是这种情况)

Oracle document on INTERSECT

答案 1 :(得分:1)

尝试此代码(未经测试)

select a.ETuid
  from tablea a
  join tableb b on (a.ETuid= b.ETuid)
 where b.fid in (1,2)
 group by a.ETuid
 having count(distinct b.fid) = 2

答案 2 :(得分:0)

这是另一种选择:

select
Etuid
from
(
 select
 TableA.Etuid, TableB.FID, 1 cnt
 from
 TableA
 join TableB on TableA.Tuid = TableB.Tuid
 where TableB.FID in (1,2)
 group by TableA.Etuid, TableB.FID
) data
group by Etuid having sum(cnt) = 2;

And here is a fiddle for it.

我为E4添加了额外的数据,因此它有2行匹配但都有FID =1

答案 3 :(得分:0)

   select a.Etuid from TableA a inner join TableB b on a.Tuid=b.Tuid 
   where b.Fid in (1,2) group by a.Etuid having count(*)>=2 order by etuid;