[SQL ] Union 與 Join 練習疑問?
小弟對SQL語法不甚了解,在練習 Union 單元時異想天開
想其他方式想達到同樣的效果。
使用資料庫:Northwind 使用表單:Orders,Customers
練習 Union 時下了這個語法:
select customerid ID,shipcity City
from orders
union
select customerid,city
from customers
出現了92筆資料。
接著實驗以下兩種方法:
1.
select distinct o.customerid ID,o.shipcity City
from orders o full join customers c
on o.customerid = c.customerid
select distinct c.customerid ID,city City
from customers c full join orders o
on c.customerid = o.customerid
order by c.customerid
2.
select customerid,city
from customers
where exists (select customerid,shipcity from orders)
order by customerid
各出現了91筆資料。
發現:
Union 的方法其中出現了兩筆重複的資料。
---------------------
| ID | City |
---------------------
|AROUT |Colchester |
|AROUT |London |
---------------------
方法1.、2.則少於Union法一筆,
只會出現上表格其中一筆。
---------------------
| ID | City |
---------------------
|AROUT |Colchester |
---------------------
或
---------------------
| ID | City |
---------------------
|AROUT |London |
---------------------
結論:
其後查詢過原始的表單,在 Orders 表單裡有筆資料裡的欄位ShipCity
與 Customers 表單設定的欄位 City 值不相同,導致做 join 與 exists
時只能出現某一個CustomerID欄位,不能出現兩個不同 City 欄位。
疑問:
這種資料庫的資料程現方式可能發生在實務的例子裡嗎?
有別的方法,可以查詢出與 Union 方法一樣的結果嗎?
(不好意思小弟第一次發文,有任何奇怪的問題請鞭小力一點>_<
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 125.224.181.181
推
11/15 10:18, , 1F
11/15 10:18, 1F
討論串 (同標題文章)