2017-01-26 50 views
0

我試圖從我的表中顯示不同的記錄,但不起作用。如果在表1中存在顯示錶2其他顯示錶1在表3中的SQL記錄

這裏我有ALL_RECORD表

ID NAME STUD_ID INFO 
1  Jose 123456 abcd 
1  Jose <null> abcd 
2  Ann  123457 abcde 
2  Ann  <null> abcde 
3  Kyle 123444 abcdq 
4  Cynt <null> abcdw 
4  Cynt 111112 abcdw 

我ALL_RECORD表中的值是從我的RECORD1和RECORD2

RECORD1表

ID NAME STUD_ID INFO 
1  Jose <null> abcd 
2  Ann  <null> abcde 
4  Cynt <null> abcdw 

RECORD2表插入

ID NAME STUD_ID INFO 
1  Jose 123456 abcd 
2  Ann  123457 abcde 
3  Kyle 123444 abcdq 
4  Cynt 111112 abcd 

我要展示的內容

ID NAME STUD_ID INFO 
1  Jose <null> abcd 
2  Ann  <null> abcde 
3  Kyle 123444 abcdq 
4  Cynt <null> abcdw 

請注意id no。 3.

我的測試QUERY1

select distinct(id), name, stud_id, info from ALL_RECORD; 

我的測試QUERY2

select * from ALL_RECORD where id is null; 

我的測試QUERY3

select * from ALL_RECORD where id is null and id in (select * from record2) group by id; 

仍然不能得到正確的輸出

+1

無關,但:'distinct'是**不是**函數。它總是適用於選擇列表中的所有**列。 'distinct(id),name'與'distinct id,name'或'distinct id,(name)'完全相同' –

+0

「如果在表1中存在顯示錶2,則顯示錶1」?因此,如果表1中的記錄不存在,我們將顯示不存在的記錄? –

回答

0

你可以用a做這個窗口函數:

select id, name, stud_id, info 
from (
    select id, name,stud_id,info, 
      row_number() over (partition by id,name order by stud_id nulls first) as rn 
    from all_record 
) t 
where rn = 1; 

的ROW_NUMBER()分配基於與order by子句中指定的排序標準的序列號。如果您希望null值具有更高的「優先級」,那麼您需要使用nulls first的非空值來爲它們指定行號1.請注意,如果組合id,name的行數多於一個空值stud_id這個選擇任意一個。

+0

它的工作原理,我不熟悉窗口函數。謝謝:) – ddddddd

0

您想要顯示所有table2記錄加上那些無法在table2中找到ID的table1記錄。

select id, name, stud_id, info from table2 
union all 
select id, name, stud_id, info from table1 where id not in (select id from table2) 
order by id; 
+0

但只有表ALL_RECORD存在 – ddddddd

+0

然後,你能寫出你的查詢#3是令人驚訝的。 –

+0

test query#3,not working – ddddddd

相關問題