![]() ![]() ![]() ![]() |
|||||
|
|||||
樓主 K.D.T ![]()
![]() |
最近在實作一個程式。 化繁為簡的表示如下: 訂單的Table 訂單編號 品名 單價...... O1 A 10 O1 B 11 O2 C 12 ...... 出貨單的Table 出貨單號 出貨日期 訂單編號 品名...... E1 2022-01-01 O1 A E3 2022-01-03 O2 C ...... 如果我要產生一張表, 有出貨沒出貨的通通列出來, 如下: 訂單編號 品名 單價 出貨日期 O1 A 10 2022-01-01 O2 B 11 O3 C 12 2022-01-03 ...... 我的做法: 先取得資料表結構, 再填入訂單資料, 再填入出貨單資料。 雖然可以達到我要的效果, 但寫法有點鳥,而且資料量一大的話,效率很差。 我記得以前學生時期選修資料庫時, 有一個複雜的 SQL 寫法, 可以一次完成我的需求, 但翻遍了所有的筆記、書,一直沒找到, 想請教各位大大, 這個 SQL 該怎麼寫? 謝謝。 使用.Net + MySQL |
1樓
作者回應
K.D.T ![]() |
自問自答 昨天在睡覺前找到了解法... 如下 Create Table trd_ord ( ord_nbr int, item_no varchar(5) ); Create Table trd_shd ( shp_nbr varchar(5), ord_nbr int, shp_date date, qty int ); Insert Into trd_ord (ord_nbr, item_no) Values (1, 'A'); Insert Into trd_ord (ord_nbr, item_no) Values (2, 'B'); Insert Into trd_ord (ord_nbr, item_no) Values (3, 'C'); Insert Into trd_ord (ord_nbr, item_no) Values (4, 'A'); Insert Into trd_ord (ord_nbr, item_no) Values (5, 'A'); Insert Into trd_shd (shp_nbr, ord_nbr, shp_date, qty) Values ('E1', 1, '2022-01-01', 10); Insert Into trd_shd (shp_nbr, ord_nbr, shp_date, qty) Values ('E2', 2, '2022-01-01', 10); Insert Into trd_shd (shp_nbr, ord_nbr, shp_date, qty) Values ('E3', 4, '2022-01-04', 10); Insert Into trd_shd (shp_nbr, ord_nbr, shp_date, qty) Values ('E4', 5, '2022-01-05', 10); select * from (select ord_nbr As seq, ord_nbr, item_no from trd_ord) As s left join (Select ord_nbr, shp_nbr, shp_date, qty From trd_shd) As t on s.ord_nbr = t.ord_nbr union select * from (select ord_nbr As seq, ord_nbr, item_no from trd_ord) As s right join (Select ord_nbr, shp_nbr, shp_date, qty From trd_shd) As t on s.ord_nbr = t.ord_nbr Order By seq; 勉強能得到我要的結果... 只是在用 DataGridView 顯示時, 要把結果的 第一列的 seq 第四列的 ord_nbr 隱藏起來,不然看起來會怪怪的, 畢竟出現兩個 ord_nbr 的 Col 及 Select 中的 ord_nbr As seq 及最後一行的 Order By seq 這兩行就只是純粹為了排序用, 原本是寫成 t.ord_nbr 或 s.ord_nbr 或 t.ord_nbr, s.ord_nbr 這三種寫法都會出現 Unknown column 'xxx' in 'order clause' 的錯誤 對此還不熟所以還沒想到解法,就暫時先這樣寫了。 以上 如果其他大神有其他更好的做法, 請不吝分享, 謝謝。
本篇文章回覆於2022-01-30 00:09
== 簽名檔 ==
--未登入的會員無法查看對方簽名檔-- |
回覆 |
如要回應,請先登入. |