Mysql 左边有条件加入右边 table
Mysql left join with condition in right table
我一直在努力解决这个问题,希望有人能帮助我。我有两个 table,第一个 table 是
Table 名称:OnlineTest
OnlineTestId category subcategory
1 English Spelling
2 English Grammar
3 English Antonyms
4 English Synonyms
第二个table是
Table 名称:用户状态
Id userId status onlineTestId
1 1 Finished 1
2 1 Not Finished 2
3 2 Not Finished 1
4 2 Finished 3
5 3 Not Finished 4
结果
OnlineTestId userId status
1 1 Finished
2 1 Not Finished
3 null null
4 null null
我试过这个查询,
select c.onlinetestid, d.userid, d.status from onlinetest c left join userstatus d on d.onlinetestid = c.onlinetestid
where c.category = 'English' and d.userid = 1;
但是这个查询带的是结果的前两行而不是后两行,其中userId和status为null。
如何把上面的结果带出来?
将 d.userid = 1
谓词放在 ON
子句中:
select c.onlinetestid, d.userid, d.status
from onlinetest c
left join userstatus d on d.onlinetestid = c.onlinetestid and d.userid = 1
where c.category = 'English'
这将 return 来自 onlinetest
的所有行,其中 userstatus
的列填充了 null
,其中谓词 d.userid = 1
失败。
您还可以使用左外连接,如下所示:
SELECT c.OnlineTestId, d.userId, d.status
FROM OnlineTest AS c LEFT OUTER JOIN
UserStatus AS d ON d.onlineTestId = c.OnlineTestId AND d.userId = 1
WHERE (c.category = 'English')
我一直在努力解决这个问题,希望有人能帮助我。我有两个 table,第一个 table 是
Table 名称:OnlineTest
OnlineTestId category subcategory
1 English Spelling
2 English Grammar
3 English Antonyms
4 English Synonyms
第二个table是
Table 名称:用户状态
Id userId status onlineTestId
1 1 Finished 1
2 1 Not Finished 2
3 2 Not Finished 1
4 2 Finished 3
5 3 Not Finished 4
结果
OnlineTestId userId status
1 1 Finished
2 1 Not Finished
3 null null
4 null null
我试过这个查询,
select c.onlinetestid, d.userid, d.status from onlinetest c left join userstatus d on d.onlinetestid = c.onlinetestid
where c.category = 'English' and d.userid = 1;
但是这个查询带的是结果的前两行而不是后两行,其中userId和status为null。
如何把上面的结果带出来?
将 d.userid = 1
谓词放在 ON
子句中:
select c.onlinetestid, d.userid, d.status
from onlinetest c
left join userstatus d on d.onlinetestid = c.onlinetestid and d.userid = 1
where c.category = 'English'
这将 return 来自 onlinetest
的所有行,其中 userstatus
的列填充了 null
,其中谓词 d.userid = 1
失败。
您还可以使用左外连接,如下所示:
SELECT c.OnlineTestId, d.userId, d.status
FROM OnlineTest AS c LEFT OUTER JOIN
UserStatus AS d ON d.onlineTestId = c.OnlineTestId AND d.userId = 1
WHERE (c.category = 'English')