我在mysql中有以下两个表:
用户:
+--------+-----------+
| userId | userName |
+--------+-----------+
| 1 | magnus |
| 2 | fabiano |
| 3 | alexander |
| 4 | veselin |
+--------+-----------+
游戏:
+--------+---------+---------+
| gameId | userId1 | userId2 |
+--------+---------+---------+
| 1 | 1 | 2 |
| 2 | 1 | 3 |
| 3 | 2 | 3 |
| 4 | 2 | 4 |
+--------+---------+---------+
我如何构建一个单一的查询,以便我得到以下输出,例如,fabiano的反对者:
输出:
+--------+-----------+
| gameId | userName |
+--------+-----------+
| 1 | magnus |
| 3 | alexander |
| 4 | veselin |
+--------+-----------+
Edit1:
这就是我的尝试,而且我无法将它们放入单个查询中:
EDIT2: 受以下答案的启发,我写了这些(他们的工作):
-- 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;
答案 0 :(得分:4)
您可以将两组数据合并在一起,即Fabiano为用户1的所有游戏,以及他所扮演的用户2所有游戏:
SELECT x.Opponent
FROM
(
SELECT u.Name AS Opponent
FROM games g
INNER JOIN users u
ON g.userId2 = u.UserId
WHERE g.UserId1 = 2 -- Fabiano
UNION
SELECT u.Name
FROM games g
INNER JOIN users u
ON g.userId1 = u.UserId
WHERE g.UserId2 = 2 -- Fabiano
) AS x;
此时假设法比亚诺不能同时成为User1
和User2
,我们需要考虑UNION ALL vs UNION DISTINCT:)
这也可以整理一下:
SELECT x.Opponent
FROM
(
SELECT u.Name AS Opponent, g.UserId1 AS PlayerId
FROM games g
INNER JOIN users u
ON g.userId2 = u.UserId
UNION
SELECT u.Name, g.UserId2 AS PlayerId
FROM games g
INNER JOIN users u
ON g.userId1 = u.UserId
) AS x
WHERE x.PlayerId = 2; -- Fabiano
答案 1 :(得分:2)
尝试类似:
SELECT `gamess`.gameId, `users`.userName
FROM users INNER JOIN
(SELECT gameId, userId2 as userId
FROM games
WHERE userId1 = 2
UNION
SELECT gameId, userId1 as userId
FROM games
WHERE userId2 = 2) AS gamess
ON `gamess`.userId = `users`.userId
答案 2 :(得分:1)
在没有UNION子句的情况下执行此操作将使其更具性能
SELECT g.gameid,
CASE WHEN u1.userid = 2 -- fabino*
THEN u2.username
else u1.username END AS Opponent
FROM games g
LEFT JOIN users u1
ON g.userId1 = u1.UserId
LEFT JOIN users u2
on g.userid2 = u2.userid
WHERE (g.UserId1 = 2 OR g.userid2 = 2) -- fabino
答案 3 :(得分:0)
选择我们。* 来自用户我们 INNER JOIN游戏gs ON us.userId = gs.userId1 GROUP BY us.userId,us.userName
答案 4 :(得分:0)
此查询应该适用于所有常见用户标识
SELECT x.Opponent
FROM
(
SELECT u.userName AS Opponent
FROM games g
INNER JOIN users u
ON g.userId2 = u.UserId
WHERE g.UserId1 in (select UserId from users where UserId in (select userid1 from games))
UNION
SELECT u.userName
FROM games g
INNER JOIN users u
ON g.userId1 = u.UserId
WHERE g.UserId2 in (select UserId from users where UserId in (select userid2 from games))
) AS x;