MySQL实现Oracle的Intersect 和 Minus

使用的两个表都非常简单,只为演示可以实现该功能。

table_a 和 table_b的结构如下:

MySQL实现Oracle的Intersect 和 Minus_第1张图片
image
MySQL实现Oracle的Intersect 和 Minus_第2张图片
image

用Oracle实现两个a、b两个表的交集

SELECT a_id as c_id,a_name as c_name from table_a  
INTERSECT  
SELECT b_id as c_id,b_name as c_name from table_b  

用Mysql实现

SELECT c_id,c_name from (  
    SELECT a_id as c_id,a_name as c_name from table_a  
    UNION ALL  
    SELECT b_id as c_id,b_name as c_name from table_b  
)a   
GROUP BY c_id,c_name  
 HAVING count(*)>1  

输出结果如下:


MySQL实现Oracle的Intersect 和 Minus_第3张图片
image.png

用Oracle实现两个a、b两个表的差集

SELECT a_id as c_id,a_name as c_name from table_a  
MINUS  
SELECT b_id as c_id,b_name as c_name from table_b  

用Mysql实现:

SELECT a.a_id,a.a_name FROM table_a a  
LEFT JOIN table_b b   
ON a.a_id = b.b_id  
WHERE a.a_name != b.b_name;  

输出结果如下:


image.png

你可能感兴趣的:(MySQL实现Oracle的Intersect 和 Minus)