Professional Documents
Culture Documents
Doing INTERSECT and MINUS in MySQL
Doing INTERSECT and MINUS in MySQL
Recently, I was asked to contribute a series of entries for the MySQL Network Knowledge
Base (to which you get access only if you’re a MySQL Network subscriber).
I thought the following ones were kind of fun, so I asked the maintainer if I would be
allowed to post them here — and maybe someone could tell me if I’m completely off-track
or have suggestions for improvements.
Updated: My esteemed colleague Dean Ellis made me aware of a couple of issues with my
suggestions, so here’s an update
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
Performing a MINUS
into something that MySQL can process, we can utilize subqueries (available from MySQL
4.1 onward). The easy-to-understand transformation is:
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:
Topics: MySQL |
1. Robin Says:
October 16th, 2005 at 9:31 pm
These examples are very usefull, however, I think it is important to comment that
internally something totally different happens. When you would do and
INTERSECT query for example, it would query the results from table A and table B
and then compare both sets. With the MySQL solution you describe it would query
all results from the first table and then do a lookup for each result in the second
table. This results in worse performance when your query returns a huge number of
results. For most uses your approach will be a good solution doh
This is realy very helpful. i have across the fact that mysql 4.0 version
has lots of limitation. coming from oracle background it is difficult to think of
writting queries when you are not sure whether this will work or not. so this kind of
website proves to be very handy. Thank you
3. talunan Says:
May 4th, 2007 at 10:05 am
5. Shubh Says:
November 21st, 2007 at 3:38 pm
I need to perform ‘minus’ between two tables. But the only field I am using in select
statement is ‘count(*)’. How to preform it?
Thanks in advance.
[...] Alternativ kann man das auch mit einem Left Join lösen. Alle Varianten haben
mit dem Original-MINUS gemein, dass sie recht unperformant sind. (Gefunden
bei bitbybit) [...]
my query is this
Bahesh Singh, this article is about how to do an intersection in MySQL. Even if the
author refers abou INTERSECT, this statement doesn’t exist in MySQL sql
language.
Actually statements
SELECT member_id, name FROM a
INTERSECT
SELECT member_id, name FROM b
and
INTERSECT and MINUS (EXCEPT) are operating on unique tuples, see example
(in Oracle but this is not relevant):