表格结构:
users: uid, name
friendships: uid1, uid2
game_membership: gid, uid
基本上我正在尝试将查询作为gid
的函数,并返回:
uid1, name1, uid2, name2
只返回给定uid
下game_membership
表中的gid
。这是我到目前为止所得到的:
SELECT
f.uid1 AS id1,
u1.name AS name1,
f.uid2 AS id2,
u2.name AS name2
FROM
friendships AS f
WHERE
u1.uid in (SELECT uid FROM game_membership WHERE gid = <GID>)
AND u2.uid in (SELECT uid FROM game_membership WHERE gid = <GID>)
JOIN users AS u1 ON f.uid1 = u1.uid
JOIN users AS u2 ON f.uid2 = u2.uid
我现在刚收到MySQL语法错误。谁能指出我正确的方向?我觉得我可能需要在uid
表的game_membership
上另外加一两个JOIN,每个uid
一个?
答案 0 :(得分:9)
我建议您加入Game_membership表而不是where子句:
SELECT
f.uid1 AS id1,
u1.name AS name1,
f.uid2 AS id2,
u2.name AS name2
FROM
friendships AS f
JOIN game_membership AS user1_gm ON user1_gm.uid = f.uid1
JOIN game_membership AS user2_gm ON user2_gm.uid = f.uid2
JOIN users AS u1 ON f.uid1 = u1.uid
JOIN users AS u2 ON f.uid2 = u2.uid
WHERE user1_gm.gid = <GID> AND user2_gm.gid = <GID>
答案 1 :(得分:1)
将加入添加到 FROM 子句中,如下所示:
FROM friends f
LEFT OUTER JOIN users u1 ON f.uid1 = u1.uid
LEFT OUTER JOIN users u2 on f.uid2 = u2.uid
答案 2 :(得分:1)
替代:
SELECT
f.uid1 AS id1,
u1.name AS name1,
f.uid2 AS id2,
u2.name AS name2
FROM friendships AS f
INNER JOIN users AS u1
ON f.uid1 = u1.uid
INNER JOIN users AS u2
ON f.uid2 = u2.uid
INNER JOIN game_membership GMS
ON GMS.UID=U1.UID
INNER JOIN game_membership GMS2
ON GMS2.UID=U2.UID
WHERE
GMS.GID= <GID> and GMS2.GID=<GID>
现在它不是保罗的替代品:D
答案 3 :(得分:1)
select uid1, u1.name as name1, uid2, u2.name as name2
from friendships
join game_membership as g1 on uid1 = g1.uid
join game_membership as g2 on uid2 = g2.uid
join users as u1 on uid1 = u1.uid
join users as u2 on uid2 = u2.uid
where g1.gid = <GID> and g2.gid = <GID>