今天公司一个同事问我一个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;
 
                    
                 
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号