简体   繁体   English

MySQL只返回另一个表中不存在列的行

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

MySQL Tables: MySQL表:

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. 预期结果是一个比较,它仅返回完整详细信息中的条目,这些条目不是基于其firstname,lastname和hometown的基本详细信息。

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. 我更擅长编写MySQL查询的PHP,所以我所有的尝试都是关于创建独特的数组并尝试对它们进行排序。 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)? 有没有一种特定的方法来返回MySQL中同时存在的两个表中的唯一值(如果有所不同,则返回MySQLi)?

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. 要获取不匹配的行集,我们可以使用OUTER连接(以便返回a中的所有行),以及来自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. 我们可以通过添加WHERE子句来做到这一点,WHERE子句是一个测试是否找到匹配的谓词。 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: 一个方便的方法是测试b中的列是否为NULL,b中的列,如果找到匹配,我们知道该列不是 NULL:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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