一尘不染

MySQL的左连接与条件在右表

mysql

我已经尝试解决这个问题一段时间了,希望有人能帮助我。我有两个桌子,第一个桌子是

表名:OnlineTest

OnlineTestId     category    subcategory                                                                   
     1            English      Spelling                                                                    
     2            English      Grammar
     3            English      Antonyms
     4            English      Synonyms

第二张表是

表名称:UserStatus

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。

如何带来以上结果?


阅读 353

收藏
2020-05-17

共1个答案

一尘不染

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'

这将返回的所有行onlinetest,其中谓词失败的列userstatus填充为。null``d.userid = 1

2020-05-17