今天公司一個同事問我一個SQL語句相關的操作,好長時間沒有使用過數據庫,突然之間還有點想不起來了的樣子。不過還好,最終還搞定,否則就丟人了!具體的問題如下:
有下面的一張表:profile,要得到to_profile中包含5但是from_profile中不包含5或者to_profile中不包含5但是from_profile中包含5的這兩個列的內容
id |
to_profile |
from_profile |
name |
address |
1 |
5 |
7 |
Aaa |
fdsff |
2 |
7 |
6 |
Bbb |
Fdaf |
3 |
7 |
6 |
Accc |
Fdafd |
4 |
2 |
6 |
Ddd |
Afddsaf |
5 |
2 |
7 |
Eee |
Dfafdaf |
6 |
2 |
5 |
Fff |
Adfd |
7 |
1 |
3 |
Ggg |
Dafd |
8 |
4 |
5 |
Ggg |
Dasfa |
9 |
3 |
5 |
dffh |
Asdfa |
具體的解決辦法如下:
通過UNION關鍵字進行集合操作查詢:
1 SELECT to_profile FROM profile WHERE from_profile=5 AND to_profile!=5 2 UNION 3 SELECT from_profile FROM profile WHERE to_profile=5 AND from_profile!=5 4 ORDER BY to_profile;
UNION關鍵字的作用是取得兩個查詢的並集但是重復的元素只取得其中的一個,如果不想去掉重復的元素,可以使用UNION ALL關鍵字。
另外有一點需要注意的是使用UNION等關鍵字的時候,查詢的字段的數據類型需要兼容。而且最終的字段名稱以第一個查詢語句為准,ORDER BY字句必須放在最后一個查詢語句的后面。
順便復習了下其他的集合查詢的關鍵字
交集:select code, name from A
intersect
select student_code,student_name from B;
差集:SELECT order_id FROM order01
MINUS
SELECT order_id FROM order02;