MYSQL |如何加入两个表来获得不同的行?

时间:2018-02-09 19:20:58

标签: mysql sql select join left-join

Skills:                       user_skills:

+-------------------------+   +--------------------------------+
| UID | Skill                 | UID | user_id | skill_id
---------------------------   +---------------------------------
|  1  | C++                   |  1  |    34   |     1
|  2  | C#                    |  2  |    34   |     2
|  3  | Python   

我的预期输出是:

+----------------------------------+
| ID(Skill ID from Skills) | Skill               
------------------------------------
| 3                        | Python     

我只想要用户34没有的技能。

目前获得用户所拥有的技能:

SELECT ss. * 
FROM skills AS s
LEFT JOIN user_skills AS us ON s.UID = us.skill_id
WHERE us.user_id = 34

但我似乎无法将逻辑降低以达到相反的目的。因为当每个用户有更多的技能时,这不起作用。

SELECT s. * 
FROM skills AS s
LEFT JOIN user_skills AS us ON s.UID != us.skill_id
WHERE us.user_id = 34

2 个答案:

答案 0 :(得分:1)

not exists运算符更适合此要求:

SELECT *
FROM   skills s
WHERE  NOT EXISTS (SELECT *
                   FROM   user_skills us
                   WHERE  us.skill_id = s.uid AND
                          us.user_id = 34)

答案 1 :(得分:1)

SELECT ss. * 
FROM skills AS s
LEFT JOIN user_skills AS us ON s.UID = us.skill_id and 
us.user =34
WHERE us.user_id is null

您正在寻找加入何时发生。用户不存在

因此用户为空