简体   繁体   中英

MySQL return only rows that's columns don't exist in another table

MySQL Tables:

Table Name: basicdetails
id,firstname,lastname,hometown
1,bob,dylan,somewhere
2,judge,judy,somewhere

Table Name: fulldetails
id,firstname,lastname,age,gender,eyes,hometown
1,bob,dylan,51,m,blue,somewhere
2,bob,dylan,22,m,green,somewhereelse
3,judge,judy,19,f,blue,somewhere
4,judge,judy,62,f,blue,somewherenicer
5,bob,dylan,31,m,blue,somewhere

Intended result is the a comparison that returns only the entries from the fulldetails that aren't in the basic details based on their firstname, lastname, and hometown only.

In this case it would be:

bob,dylan,somewhereelse
judge,judy,somewherenicer

I am better at PHP that writing MySQL queries so all of my attempts have been about creating unique arrays and trying to sort through them. It's very complicated and very slow so I was thinking maybe it was possible to get the entries that don't exist in both based on their (firstname,lastname,hometown) only. Is there a specific way to return the unique values that don't exist in both tables at the same time with MySQL (or MySQLi if that makes a difference)?

My apologies for the wording on this, I am having trouble wording it correctly.

An anti-join is a familiar pattern.

You already know how to find rows that have matches:

SELECT a.*
  FROM a
  JOIN b
    ON a.firstname = b.firstname
   AND a.lastname  = b.lastname
   AND a.hometowm  = b.hometown

To get the set of rows that don't match, we can use an OUTER join (so that all rows from a are returned), along with matching rows from b.

SELECT a.*
  FROM a
  LEFT
  JOIN b
    ON a.firstname = b.firstname
   AND a.lastname  = b.lastname
   AND a.hometowm  = b.hometown

The "trick" now is to filter out all the rows that had matches. We can do this by adding a WHERE clause, a predicate that tests whether a match was found. A convenient way to do this, is to test whether a column from b is NULL, a column from b that we know would not be NULL if a match was found:

SELECT a.*
  FROM a
  LEFT
  JOIN b
    ON a.firstname = b.firstname
   AND a.lastname  = b.lastname
   AND a.hometowm  = b.hometown
 WHERE b.firstname IS NULL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM