繁体   English   中英

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

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

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

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

在这种情况下,它将是:

bob,dylan,somewhereelse
judge,judy,somewherenicer

我更擅长编写MySQL查询的PHP,所以我所有的尝试都是关于创建独特的数组并尝试对它们进行排序。 它非常复杂而且非常慢,所以我想也许有可能只根据它们(名字,姓氏,家乡)获得两者中不存在的条目。 有没有一种特定的方法来返回MySQL中同时存在的两个表中的唯一值(如果有所不同,则返回MySQLi)?

对于这方面的措辞,我道歉,我无法正确写字。

反连接是一种熟悉的模式。

您已经知道如何查找具有匹配项的行:

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

要获取不匹配的行集,我们可以使用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

现在的“技巧”是过滤掉所有匹配的行。 我们可以通过添加WHERE子句来做到这一点,WHERE子句是一个测试是否找到匹配的谓词。 一个方便的方法是测试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