0

JOIN我在 MySQL 中创建了一个相对简单的查询,根据名字和姓氏的匹配位置为我提供三个表。从那里,我想编写另一个查询,然后只向我显示匹配的记录JOIN——但我不知道该怎么做。我假设它与使用涉及类似于NOT IN我的原始查询的子查询有关,但我无法得到它给我想要的结果。

这是我试图提出的解决方法,部分功能正常:

SELECT *, 
  if(t2.first=t1.first AND t2.last=t1.last, "Match", "No Match") AS "t2 Match",
  if(t3.first=t1.first AND t3.last=t1.last, "Match", "No Match") AS "t3 Match"
FROM t1
LEFT JOIN t2 ON t2.first=t1.first AND t2.last=t1.last
LEFT JOIN t3 ON t3.first=t1.first AND t3.last=t1.last
WHERE if(t2.first=t1.first AND t2.last=t1.last, "Match", "No Match")="No Match"
   OR if(t3.first=t1.first AND t3.last=t1.last, "Match", "No Match")="No Match";

我觉得这是相当简单直接的事情,但我没有得到正确的结果。有人可以帮忙吗?

谢谢!

4

1 回答 1

5

不匹配意味着t2(或t3)列在结果中填充了 Null。所以你可以使用IS NULL检查:

SELECT t1.*
FROM t1
  LEFT JOIN t2 ON t2.first = t1.first AND t2.last = t1.last
  LEFT JOIN t3 ON t3.first = t1.first AND t3.last = t1.last
WHERE t2.first IS NULL
   OR t3.first IS NULL ;

您是对的,您还可以使用以下方法编写查询NOT IN(警告:仅当连接列不可为空时。否则您可能会得到意想不到的结果):

SELECT t1.*
FROM t1
WHERE (first, last) NOT IN
      ( SELECT first, last  FROM t2 )
   OR (first, last) NOT IN
      ( SELECT first, last  FROM t3 )
  ;

或使用NOT EXISTS

SELECT t1.*
FROM t1
WHERE NOT EXISTS 
      ( SELECT 1
        FROM t2
        WHERE t1.first = t2.first
          AND t1.last = t2.last
      )
   OR NOT EXISTS 
      ( SELECT 1
        FROM t3
        WHERE t1.first = t3.first
          AND t1.last = t3.last
      ) ;
于 2013-06-27T18:09:16.567 回答