欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

MySQL不支持INTERSECT和MINUS及其替代方法

程序员文章站 2024-02-29 10:16:34
doing intersect and minus in mysql doing an intersect an intersect is simply an inner...
doing intersect and minus in mysql

doing an intersect

an intersect is simply an inner join where we compare the tuples of one table with those of the other, and select those that appear in both while weeding out duplicates. so

复制代码 代码如下:

select member_id, name from a
intersect
select member_id, name from b


can simply be rewritten to

复制代码 代码如下:

select a.member_id, a.name
from a inner join b
using (member_id, name)


performing a minus
to transform the statement

复制代码 代码如下:

select member_id, name from a
minus
select member_id, name from b


into something that mysql can process, we can utilize subqueries (available from mysql 4.1 onward). the easy-to-understand transformation is:

复制代码 代码如下:

select distinct member_id, name
from a
where (member_id, name) not in
(select member_id, name from table2);


of course, to any long-time mysql user, this is immediately obvious as the classical use-left-join-to-find-what-isn't-in-the-other-table:

复制代码 代码如下:

select distinct a.member_id, a.name
from a left join b using (member_id, name)
where b.member_id is null