如何使用自联接

时间:2015-05-12 14:03:28

标签: mysql self-join

所以,让我们说我有一个名为users的表,其中包含以下列:

 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;

这不应该从别名表switch_from中删除别名表switch_to中的所有job_id吗?

这将返回唯一具有匹配job_id的行。

3 个答案:

答案 0 :(得分:1)

我认为你也可以使用减号:

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;

如果你想在switch_to中使用switch_to中的记录,那么就可以这样做。

binIO_t

答案 1 :(得分:1)

试试这样:

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;

答案 2 :(得分:1)

尝试此查询:

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