从2个表中选择,2个外键具有1个异常值| MySQL的

时间:2016-05-22 18:16:05

标签: mysql join foreign-keys

我正在尝试为以下问题创建一个sql语句: 我有两张桌子:

**Table user**
    user_id      |  user_name
    1            |  Carl
    2            |  Claudia
    3            |  Janet
    4            |  Ben

**Table matching**
    matching_id  |    user_id_1_FK  |    user_id_2_FK
    1            |    1             |    2
    2            |    3             |    1
    3            |    4             |    2 

现在想要列出所有匹配/对,其中用户carl正在成为其中的一部分

结果应为:

user_name    | user_id
Claudia      | 2
Janet        | 3

请提前获得帮助。

2 个答案:

答案 0 :(得分:2)

这样的查询的增值对我来说不是很明显,但在玩了一下之后,我想出了以下解决方案:

SELECT DISTINCT other_user_id, target.user_name
FROM (
    select user_id_1_FK as leading_user_id, user_id_2_FK as other_user_id
    from matching

    union all

    select user_id_2_FK as leading_user_id, user_id_1_FK as other_user_id
    from matching
) as allmatching 
LEFT JOIN user as target on allmatching.other_user_id = target.user_id
RIGHT JOIN user as source on allmatching.leading_user_id = source.user_id
WHERE source.user_name = 'Carl';

诀窍在于,显然,您的匹配表正在指定一个双向属性:从哪一侧读取它并不重要。要将其纳入查询,正在使用UNION操作。之后,只需加入user表两次就可以使用" natural"术语而不是代理ID。

答案 1 :(得分:1)

E.g:

DROP TABLE IF EXISTS user;

CREATE TABLE user
(user_id      INT NOT NULL PRIMARY KEY
,user_name VARCHAR(12) NOT NULL
);

INSERT INTO user VALUES
(1,'Carl'),
(2,'Claudia'),
(3,'Janet'),
(4,'Ben');

DROP TABLE IF EXISTS matching;

CREATE TABLE matching
(user_id1 INT NOT NULL
,user_id2 INT NOT NULL
,PRIMARY KEY (user_id1,user_id2)
);

INSERT INTO matching VALUES
(1,2),
(3,1),
(4,2);

SELECT u.* 
  FROM user u 
  JOIN matching m  
    ON u.user_id IN(m.user_id1,m.user_id2) 
  JOIN user x 
    ON x.user_id IN(m.user_id1,m.user_id2) 
 WHERE x.user_name = 'Carl' 
   AND x.user_id <> u.user_id;
+---------+-----------+
| user_id | user_name |
+---------+-----------+
|       2 | Claudia   |
|       3 | Janet     |
+---------+-----------+