【发布时间】:2015-01-03 08:15:58
【问题描述】:
我在mysql中有以下两个表:
用户:
+--------+-----------+
| userId | userName |
+--------+-----------+
| 1 | magnus |
| 2 | f*o |
| 3 | alexander |
| 4 | veselin |
+--------+-----------+
游戏:
+--------+---------+---------+
| gameId | userId1 | userId2 |
+--------+---------+---------+
| 1 | 1 | 2 |
| 2 | 1 | 3 |
| 3 | 2 | 3 |
| 4 | 2 | 4 |
+--------+---------+---------+
我怎样才能构造一个单一的查询,这样我才能得到下面的输出,比如说,f*o 的对手:
输出:
+--------+-----------+
| gameId | userName |
+--------+-----------+
| 1 | magnus |
| 3 | alexander |
| 4 | veselin |
+--------+-----------+
编辑1:
这是我正在尝试的,但我无法将它们放入单个查询中:
- 选择 f*o 的对手 [select * from games where 2 in (userId1, userId2);]
- 读取每一行,检查哪一行是f*o(2),然后选择另一个userId
- 从这些对手的 userIds 中,从 users 表中获取他们的名字
编辑2: 受以下答案的启发,我写了这个(它们有效):
-- NO JOIN
select x.gameId, users.userName from
(
select gameId, userId2 as id from games where userId1=2
UNION
select gameId, userId1 as id from games where userId2=2
) as x, users
where users.userId = id;
-- NO JOIN, NO UNION
select x.gameId, users.userName from (
SELECT g.gameId,
CASE WHEN userId1 = 2
THEN userId2
WHEN userId2 =2
THEN userId1
END AS id
FROM games g) as x, users
where users.userId = id;
【问题讨论】:
-
听起来像是为我工作
-
对不起,如果听起来是这样……请给点指示/提示?
-
使用查询获取对手为userId1,编写相同查询获取对手为userId2,并使用联合将两个查询合并。
-
@ZeRuBuES 我不这么认为;-)