MySQL:查询互斥记录集

MySQL: Query mutually exclusive record sets

我有一个 mysql table 类似于:

+----+----------+----------+
| id | first    | last     +
+----+----------+-----------
|  5 | Alan     | Smith    |
|  5 | Bob      | Jones    |
|  5 | Tom      | Clark    |
|  5 | Victor   | Mars     |
|  6 | Bob      | Jones    |
|  6 | Tom      | Kelly    |
|  6 | Victor   | Mars     |
+----+----------+----------+

我想找到一个高效的查询,它可以 return 所有在 id 5 和 id 6 之间不匹配的记录...像这样:

+----+----------+----------+
| id | first    | last     +
+----+----------+-----------
|  5 | Alan     | Smith    |
|  5 | Tom      | Clark    |
|  6 | Tom      | Kelly    |
+----+----------+----------+

目前,我正在使用 2 个单独的查询,return 2 个不同的 "not in" 集,如下所示 select。其中 5 不在 6 中且 6 不在 5 中。

select id,
       first,
       last
  from mytable
 where id = 5  # swap 5 and 6
   and concat(first, last) 
       not in ( select concat(first, last) 
                  from mytable
                where id = 6 )   # swap 5 and 6
      group by id,
               first,
               last

有没有办法在单个查询中获取这两个集合?您能否提供使用此示例数据的示例?

有没有比我的查询更高效的方法?另外,举个例子。谢谢

试试这个。它执行自连接并使用 LEFT 连接来查看是否没有匹配项。如果 table (mt2) 的第二个实例中没有匹配项,则 table 中的所有字段都将 return NULL。因为我猜测 id 字段是 table 上的主键,我猜它永远不应该是 NULL.

select mt1.id,
       mt1.first,
       mt1.last

from mytable mt1

     LEFT JOIN mytable mt2
     ON mt1.first = mt2.first
     AND mt1.last = mt2.last
     AND mt2.id IN (5, 6)
     AND mt1.id <> mt2.id

where mt1.id IN (5, 6)
     AND mt2.id IS NULL
;

我用id表示自动递增的PK。这里显然不是这种情况,所以为了便于理解,我将该列重命名了...

SELECT x.*  
  FROM my_table x 
  LEFT 
  JOIN my_table y 
    ON y.group_id <> x.group_id 
   AND y.first = x.first 
   AND y.last = x.last 
 WHERE x.group_id IN(5,6) 
   AND y.group_id IS NULL;