我有两个表,我正在尝试完成一个完整的外连接。
availability
availability_id availability_desc
1 Monday Morning
2 Monday Afternoon
3 Monday Evening
etc
user_availability
user_id availability_id
1 1
1 3
etc
SELECT * from availability a left outer join user_availability u
on a.availability_id=u.availability_id;
给出了结果:
availability_id; availability_desc; id; user_id; availability_id
1; Monday Morning; 1; 1; 1
1; Monday Morning; 15; 2; 1
1; Monday Morning; 40; 4; 1
1; Monday Morning; 57; 5; 1
2; Monday Afternoon; 2; 1; 2
3; Monday Evening; 16; 2; 3
3; Monday Evening; 42; 4; 3
相同表格上的右外连接导致:
availability_id availability_desc id user_id availability_id
1 Monday Morning 1 1 1
2 Monday Afternoon 2 1 2
4 Tuesday Morning 3 1 4
右外连接和左外连接的并集给出了以下结果:
availability_id availability_desc id user_id availability_id
1 Monday Morning 1 1 1
1 Monday Morning 15 2 1
1 Monday Morning 40 4 1
1 Monday Morning 57 5 1
2 Monday Afternoon 2 1 2
2 Monday Afternoon 30 3 2
2 Monday Afternoon 41 4 2
3 Monday Evening 16 2 3
3 Monday Evening 42 4 3
当其他表中没有匹配项时,我没有返回任何空值。我希望生成如下所示的结果:
availability_desc user_id
Monday Morning 1
Monday Afternoon 1
Monday Evening (null)
不确定我做错了什么。
答案 0 :(得分:0)
如果要为每个用户显示一条记录,对于每个可用性,是否有匹配的记录,这都可以解决问题。这假设有一个名为user
的表,其中包含系统中的所有用户。使用CROSS JOIN
可以获取每个可用性记录的每个用户记录。然后将这两个表连接到user_availability表将查看用户是否可用。
SELECT *
FROM availability a
cross join user u
LEFT JOIN user_availability ua
on u.user_id = ua.user_id
AND a.availability_id = ua.availability_id
;
这是一个更易读的版本,加上一个sqlfiddle。
SELECT availability_desc,
user_name,
CASE WHEN ua.user_id IS NULL THEN 'Not Available' ELSE 'Available' END AS availability
FROM availability a
cross join user u
LEFT JOIN user_availability ua
on u.user_id = ua.user_id
AND a.availability_id = ua.availability_id
;
sqlfiddle:http://www.sqlfiddle.com/#!2/626489/4