iT邦幫忙

0

SQL篩選2個 Table 缺少的欄位

XYZ 2023-03-20 13:53:40996 瀏覽
  • 分享至 

  • xImage

SQL篩選2個 Table 尋找B Table缺少的欄位,希望的結果如圖三,下面的SQL哪裡錯?

select a.order as a_order,a.no as a_no, b.order as b_order,b.no as b_no
from a
left join b on b.order=a.order and b.no=a.no
where b.no is null

https://ithelp.ithome.com.tw/upload/images/20230320/201081578kgImU24iW.png

https://ithelp.ithome.com.tw/upload/images/20230320/20108157qoxs56Aj4s.png

https://ithelp.ithome.com.tw/upload/images/20230320/20108157FG07mOuYOE.png

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
allenlwh
iT邦高手 1 級 ‧ 2023-03-20 14:06:34
select a.order as a_order,a.no as a_no, b.order as b_order,b.no as b_no
from a
left join b on b.order=a.order and b.no=a.no
where b.no is null
看更多先前的回應...收起先前的回應...
XYZ iT邦新手 4 級 ‧ 2023-03-20 14:14:52 檢舉

不好意思,原始的誤打where b.b.no is null, 我下where b.no is null 仍找不出我要的結果,SQL查出的結果是找不到,再麻煩您解惑,謝謝

allenlwh iT邦高手 1 級 ‧ 2023-03-20 14:22:00 檢舉
select a.[order] as a_order,a.no as a_no, b.[order] as b_order,b.no as b_no
from a
left join b on b.[order]=a.[order] and b.no=a.no
where b.no is null

https://ithelp.ithome.com.tw/upload/images/20230320/20033493UEWdsYFiQZ.jpg

allenlwh iT邦高手 1 級 ‧ 2023-03-20 14:22:30 檢舉
select a.[order] as a_order,a.no as a_no, b.[order] as b_order,b.no as b_no
from a
left join b on b.[order]=a.[order] and b.no=a.no
where b.no is null
XYZ iT邦新手 4 級 ‧ 2023-03-20 14:51:05 檢舉

我用where b.no is not null,會顯示2個資料庫符合的資料, 但用
where b.no is null 就找不到任何資料...不知哪有問題?

allenlwh iT邦高手 1 級 ‧ 2023-03-20 14:56:41 檢舉

1.看一下 table a 和 table b的資料型態
2.檢查一下資料內容,是否有空白

BeEvil_Y iT邦新手 4 級 ‧ 2023-03-20 15:57:44 檢舉

null不等於空白,在資料庫他會寫一個null英文字在上面。
只要沒寫就不是。

allenlwh iT邦高手 1 級 ‧ 2023-03-20 16:06:56 檢舉
select a.[order] as a_order,a.no as a_no, b.[order] as b_order,b.no as b_no
from a
left join b on b.[order]=a.[order] and b.no=a.no
where isnull(b.no,'')=''
XYZ iT邦新手 4 級 ‧ 2023-03-20 16:51:24 檢舉

1.資料欄位沒空白欄位
2.where isnull(b.no,'')='' 結果仍找不到資料

alien663 iT邦研究生 4 級 ‧ 2023-03-21 11:25:37 檢舉

allenlwh回答的就是正確答案,利用left join或是right join時對應不到資料會是null的特性,優化差集查詢,如果要用left join去找出A、B table的差集,那算是滿普遍的寫法。
如果資料不盡你意,你也可以利用except語法先進行排查,看看是否A、B存在差集,下b.no is null這個條件的用意,是找出B-A的部分,如果改成b.no > '',那結果應該是跟inner join是一樣的,結果應該會是A、B的交集。
結果跟你想像的不一樣,有可能有以下原因:

  1. 資料不存在差集,所以找不出資料
  2. left join條件下錯

另外,allenlwh的程式碼有一點可以學習,當使用保留字(SSMS中看起來是藍色的)作為欄位名稱使用,盡量使用[]包住欄位名稱,雖然MSSQL現在的優化應該不會有問題了,不過這是一個良好的程式編寫習慣,值得學習。

關於資料表集合概念,可以參考文章 : 資料表集合與文氏圖

我要發表回答

立即登入回答