[英]Mysql left join with condition in right table
I have been trying to solve this issue for a while, hope anyone help me.我一直在努力解决这个问题,希望有人帮助我。 I am having two table, the first table is
我有两张桌子,第一张桌子是
Table Name : OnlineTest表名:在线测试
OnlineTestId category subcategory
1 English Spelling
2 English Grammar
3 English Antonyms
4 English Synonyms
The second table is第二张表是
Table Name : 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
Result结果
OnlineTestId userId status
1 1 Finished
2 1 Not Finished
3 null null
4 null null
I have tried this query,我试过这个查询,
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;
But this query is bring the first two row of the result and not the last two, in which the userId and status are null.但是这个查询是带结果的前两行而不是最后两行,其中userId和status为空。
How to bring the above result?如何带来上述结果?
Place the d.userid = 1
predicate in the ON
clause:将
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'
This will return all rows from onlinetest
, having columns of userstatus
filled with null
s where predicate d.userid = 1
fails.这将返回来自
onlinetest
所有行,其中userstatus
列填充了null
s,其中谓词d.userid = 1
失败。
You can also use left outer Join as below :您还可以使用左外连接,如下所示:
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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.