查询以获取特定列的所有匹配项

时间:2010-10-15 02:45:47

标签: sql oracle

假设我有两个表Table1和Table2,其中包含以下数据。

Column1 Column2 Column3
AAA      KKK       9
BBB      LLL       7
CCC      MMM       9
DDD      MMM       5
EEE      MMM       7
FFF      NNN       9
GGG      OOO       1


Column4 Column1
TTT      DDD
TTT      BBB
UUU      EEE
VVV      BBB
WWW      AAA
WWW      BBB
XXX      DDD
YYY      EEE
YYY      DDD
YYY      CCC
YYY      FFF

当column2的值为'MMM'('CCC','DDD','EEE')时,查询选择“column4中的select值与column1的元组结果匹配”,此结果应与所有匹配第4列的结果“ 结果是'YYY'

错误消息是

    SELECT DISTINCT t2.Column4
     FROM Table1 t1
LEFT JOIN Table2 t2 ON t1.Column1 = t2.Column1
    WHERE Column2 = 'MMM'
 GROUP BY t1.Column2
   HAVING COUNT(t1.Column1) = COUNT(t2.Column1)
         *
    ERROR at line 1:
 ORA-00904: "T1"."Column1": invalid identifier

1 个答案:

答案 0 :(得分:3)

   SELECT t2.Column4
     FROM Table1 t1
LEFT JOIN Table2 t2 ON t1.Column1 = t2.Column1
    WHERE Column2 = 'MMM'
 GROUP BY t2.Column4
   HAVING COUNT(t1.Column1) = COUNT(t2.Column4)

这个查询怎么样?