如何从三个或更多表中获取数据

时间:2013-05-02 11:23:30

标签: sql oracle

我需要在三个表之间显示不同的数据。如何做这个要求。

FirstTable:

9999999999                     
8888888888           
7777777777
6666666666
5555555555

SecondTable:

7777777777
9999999999

ThirdTable:

8888888888

我希望以这种格式输出。

6666666666
5555555555

6 个答案:

答案 0 :(得分:1)

使用LEFT JOIN

   SELECT T1."Col"
     FROM Table1 T1
LEFT JOIN Table2 T2 
       ON T1."Col" = T2."Col"
LEFT JOIN Table3 T3 
       ON T1."Col" = T3."Col"
    WHERE T2."Col" IS NULL 
      AND T3."Col" IS NULL 

输出:

|        COL |
--------------
| 6666666666 |
| 5555555555 |

See this SQLFiddle

答案 1 :(得分:1)

对于您提供的数据,您可以尝试:

    select YourColumn from Table1
minus
    select Yourcolumn from Table2
minus
    select YourColumn from Table3

然而,这不会为您提供表3中存在的条目,但不会为您提供表1 ND 2.我建议您改进问题。

答案 2 :(得分:0)

试试这个......

Select yourColumn 
from Table1 
where yourColumn  not in
   ( select yourColumn  from Table2) 
and yourColumn  not in 
  (select yourColumn  from table3)

答案 3 :(得分:0)

尝试:

SELECT Column FROM FirstTable
WHERE Column NOT IN
    (SELECT Column from SecondTable UNION 
    SELECT Column from ThirdTable)

答案 4 :(得分:0)

您的结果不会显示不同的数据。它显示任何OTHER表中不是IN的数据

所以你可以写这样的

    CREATE TABLE FirstTable (VALUE VARCHAR(10))

    CREATE TABLE SecondTable (VALUE VARCHAR(10))

    CREATE TABLE ThirdTable (VALUE VARCHAR(10))

    INSERT INTO FirstTable VALUES(9999999999)                     
    INSERT INTO FirstTable VALUES(8888888888)
    INSERT INTO FirstTable VALUES(7777777777)
    INSERT INTO FirstTable VALUES(6666666666)
    INSERT INTO FirstTable VALUES(5555555555)


    INSERT INTO SecondTable VALUES(9999999999)                     
    INSERT INTO SecondTable VALUES(7777777777)

    INSERT INTO ThirdTable VALUES(8888888888)

    SELECT a1.vALUE FROM (SELECT a.vALUE FROM FirstTable a 
        LEFT OUTER JOIN SecondTable b ON A.VALUE=B.VALUE
            WHERE   b.VALUE IS NULL) a1
        LEFT OUTER JOIN ThirdTable c ON  A1.VALUE=C.VALUE
        WHERE c.VALUE IS NULL

答案 5 :(得分:0)

与流行的倾向相反,我认为这是一个很好的问题!

以下解决方案在三个表中找到 all unique values

with middle_tab as(
select t1.id t1_id,t2.id t2_id,t3.id t3_id from tab1 t1
full outer join tab2 t2 on t1.id=t2.id
full outer join tab3 t3 on t1.id=t3.id
 )

  select coalesce(t1_id,t2_id,t3_id) unique_ids from (
select t1_id,t2_id,t3_id,NVL2(t1_id,0,1)+NVL2(t2_id,0,1)+NVL2(t3_id,0,1) b
 from middle_tab)
where b>1

这是 SQL Fiddle Demo!