我有两张桌子:
TblAchievements>> [ID,AchName]
TblUsersAchievements>> [UserID,AchID]
我需要结果是这样的(假设有4个成就,用户1已经达到1和2:
ID AchName UserID AchID
1 first 1 1
2 second 1 2
3 third NULL NULL
4 fourth NULL NULL
我尝试过这样的事情:
SELECT
tblacheivements.id,
tblacheivements.achname,
tbluserachievements.uid,
tbluserachievements.achid
FROM
tbluserachievements
RIGHT OUTER JOIN tblacheivements ON (tbluserachievements.achid = tblacheivements.id)
WHERE
tbluserachievements.uid = 1 OR
tbluserachievements.uid IS NULL
它获得了正确的结果但是当我更改用户时结果是错误的。
答案 0 :(得分:2)
您似乎想要列出特定用户拥有或不拥有的所有成就。要过滤UserID
,但仍保留结果集中的每个成就行,您必须在外连接条件中包含UserID
选择(将其放在WHERE
子句中只会选择用户获得成就的行,因为WHERE
/ FROM
后会对JOIN
进行评估。)
试试这个解决方案:
SELECT *
FROM tblachievements a
LEFT JOIN tbluserachievements b ON a.id = b.achid AND b.uid = 1
<强>附加强>
根据您的应用程序要求,也许最好只设置一个布尔值来指示用户是否已实现(1
如果有,0
如果没有):
SELECT a.*, b.achid IS NOT NULL AS achieved
FROM tblachievements a
LEFT JOIN tbluserachievements b ON a.id = b.achid AND b.uid = 1
哪会产生:
id achname achieved
---------------------------
1 first 1
2 second 1
3 third 0
4 fourth 0