如何使用自连接获取不匹配的记录

How to get unmatching records using self join

假设我有一个名为 users 的 table,其中包含以下列:

 user_id (int), 
 job_id (int),
 created (date)

我想抓取两个用户,根据job_id得到不匹配的记录。

示例

user_id  | job_id | created 

15242    |  234   | 2015-04-07 
15242    |  441   | 2015-04-08
15242    |  345   | 2015-04-08
24521    |  234   | 2015-04-09

我想要 job_ids 441 和 345。

因此需要自连接

SELECT users.job_id
FROM users as switch_from
LEFT JOIN users as switch_to ON switch_from .job_id = switch_to .job_id
WHERE switch_from.user_id = 15242 AND switch_to.user_id = 24521;

这难道不应该给我别名 table switch_from 别名 table switch_to 中丢失的所有 job_ids 吗?

这是 returns 唯一匹配 job_id 的行。

我想你也可以使用减号语句:

SELECT member_id, name FROM a
MINUS
SELECT member_id, name FROM b

如果您想要 switch_to 中没有在 switch_from 中的记录,可以这样做。

SELECT users.job_id FROM users as switch_to
WHERE switch_to.user_id = 24521
MINUS
SELECT users.job_id FROM users as switch_from
WHERE switch_from.user_id = 15242;

这样试试:

SELECT switch_from.job_id
FROM users as switch_from
LEFT JOIN users as switch_to ON switch_from.job_id = switch_to.job_id AND switch_to.user_id = 24521
WHERE switch_from.user_id = 15242 AND switch_to.user_id IS NULL;

试试这个查询:

SELECT users.job_id FROM users as switch_from
   LEFT JOIN users as switch_to ON 
   ( switch_from .job_id = switch_to .job_id and switch_to.user_id = 24521 )
   WHERE switch_from.user_id = 15242