用 exists 和 not exists求集合的交集(intersection)和差集(except)及除法

用 exists 和 not exists求集合的交集(intersection)和差集(except)及除法
(本文中所有SQL语句均在Mysql v5.1中验证)




求交集intersection和差集except可以用 (A in B 或 A exists B 或 =some)和 (A not in B 或 A not exists B 或 <>all)处理:如下


mysql> select * from a;
+------+------+---------------------+
| id   | name | Date                |
+------+------+---------------------+
|    1 | A1   | 2011-07-01 00:00:00 |
|    2 | A2   | NULL                |
|    3 | A3   | NULL                |
+------+------+---------------------+
3 rows in set (0.00 sec)


mysql> select * from b;
+------+------+------+
| id   | aid  | name |
+------+------+------+
|    1 |    1 | B1   |
|    2 |    2 | B2   |
|    3 |    2 | B3   |
+------+------+------+
3 rows in set (0.00 sec)




用exists求表a的id列和表b的aid列的交集(a.id ∩ b.aid)。
mysql> select id from a where  exists (select * from b where a.id=b.aid);
+------+
| id   |
+------+
|    1 |
|    2 |
+------+
2 rows in set (0.00 sec)




用exists求表a的id列和表b的aid列的差集(a.id - b.aid):
mysql> select id from a where not exists (select * from b where a.id=b.aid);
+------+
| id   |
+------+
|    3 |
+------+
1 row in set (0.00 sec)




求除法请参考另外一份文档:exists和not exists的嵌套使用及求关系的除法.txt
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值