MySQL中实现并、交、差

x33g5p2x  于2021-10-04 转载在 Mysql  
字(0.6k)|赞(0)|评价(0)|浏览(503)

简介

sql叫做结构化查询语言,本质利用的就是关系代数中的操作,比如常用的并、交、差、投影、选择等操作。

其中并、交、差是常用的操作,本文就看看MySQL中的sql语言是怎么提供对应的关系代数操作的。

并的符号是∪,含义就是将两个集合合并到一块。

MySQL中提供的是union关键字,会去重

select id from A union select id from B;  //A B数据结构一定要一样

MySQL中还提供了union all 关键字,不会过滤重复元素。

select id from A union all select id from B;  //A B数据结构一定要一样

交的符号是∩,含义是取两个集合的共同元素。

MySQL中没有直接提供求交集的关键字,我们可以通过其他关键字来模拟实现

1、in

select id from A where id in (select id from B);

通过 in 来选择A中的元素,选择条件就是A中的元素需要在B中出现

2、join

通过内连接

select A.id from A inner join B where A.id = B.id;

差的符号是 - ,A - B的含义是 只存在于A集合中,而不存在于B集合中的元素。

MySQL没有对应的直接操作符,也可以通过其他操作符来操作。

1、not in

select id from A where id not in (select id from B);

2、join

使用leftjoin

select A.id  from A left join B on A.id = B.id where B.id is null;

相关文章

微信公众号

最新文章

更多