sql-server-2008 – SQL右外连接,右表中没有匹配项

无论如何可以进行SQL查询,从左表中获取一些信息,从右表中获取符合条件的所有信息.

但是如果没有与右表中的条件匹配的记录,它仍应显示完整记录,但填充了大量* NULL * s

此刻,我来到这里:

select
 u.id, u.fullname,
 r.*
from
 users as u
right outer join
 rapports as r
on
 u.id = r.userid
where
 u.active = 1
 and (r.closed = 0 or CONVERT(varchar, r.periodstart, 112) = convert(varchar, GETDATE(), 112))
order by
 u.fullname

但是,如果rapports-table中的记录与WHERE条件匹配,则仅显示来自user-table的记录.

无论如何可能吗?

最佳答案 请注意外部表(r)的条件在何处 – 不在WHERE子句中(将外部联接转换为内部联接),而是在ON子句中.

select
 u.id, u.fullname,
 r.*
from
 users as u
left outer join
 rapports as r
on
 u.id = r.userid
 and (r.closed = 0 
   or CONVERT(varchar, r.periodstart, 112) = convert(varchar, GETDATE(), 112))
where
 u.active = 1
order by
 u.fullname;

然而,这要好得多:

select
 u.id, u.fullname,
 r.*
from
 users as u
left outer join
 rapports as r
on
 u.id = r.userid
 and (r.closed = 0 or CONVERT(DATE, r.periodstart) = CONVERT(DATE, GETDATE()))
where
 u.active = 1
order by
 u.fullname;
点赞