简体   繁体   English

如何实现sql查询以基于2列进行外部联接

[英]How to implement sql Query to do Outer Joins based on 2 columns

I have Table x containing Courses done by Users but another Table y containing courses assigned to users. 我的表x包含用户完成的课程,但另一个表y包含分配给用户的课程。 I need to retrieve all courses with null row if user doesn't complete the Course 如果用户未完成课程,则需要检索所有行为空的课程

[Table M] [Table X] [Table Y] [表M] [表X] [表Y]
UserId UserId Cid CourseId UserId UserId Cid CourseId
1 1 1 1 2 1 1 1 1 2
2 2

I need 我需要

[Table Z]

[UserId] [CourseId] [F] [UserId] [CourseId] [F]
1 1 done 1 1完成
1 2 not done 1 2未完成
2 2 not done 2 2未完成
2 1 not done 2 1未完成

You could do something like this 你可以做这样的事情

SQL Fiddle Example SQL小提琴示例

SELECT tm.userid,
  ty.courseid,
  CASE WHEN tx.cid IS NULL THEN 'not done' ELSE 'done' END AS 'F'
FROM tablem tm
JOIN tabley ty ON 1=1
LEFT JOIN tablex tx ON tm.userid = tx.userid AND ty.courseid = tx.cid
ORDER BY tm.USERID

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM