【问题标题】:Mysql left join with condition in right tableMysql左连接与右表中的条件
【发布时间】:2015-10-28 10:17:57
【问题描述】:

我一直在尝试解决这个问题,希望有人能帮助我。我有两张桌子,第一张桌子是

表名:在线测试

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

第二张表是

表名:用户状态

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为空。

如何带来以上结果?

【问题讨论】:

  • 将 where 条件移至 on 子句 on d.onlinetestid = c.onlinetestid and c.category = 'English' and d.userid = 1

标签: mysql left-join where


【解决方案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 的列用nulls 填充,其中谓词d.userid = 1 失败。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2011-04-29
      • 2020-07-28
      • 1970-01-01
      • 1970-01-01
      • 2013-09-13
      • 1970-01-01
      • 2015-10-31
      • 2013-08-23
      • 1970-01-01
      相关资源
      最近更新 更多