MySQL不支持INTERSECT和MINUS及其替代方法
程序员文章站
2024-03-31 14:29:10
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
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
上一篇: MySQL 导出数据为csv格式的方法