Mysql左边的连接条件在右表中

时间:2015-08-05 14:50:46

标签: mysql left-join where

我一直试图解决这个问题一段时间,希望有人帮助我。我有两张桌子,第一张桌子是

表名: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。

如何得出上述结果?

2 个答案:

答案 0 :(得分:9)

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 s,其中谓词d.userid = 1失败。

答案 1 :(得分:0)

您也可以使用左外连接,如下所示:

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')