4

是否有可能进行 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

但这仅显示user-table是否有rapports-table匹配条件的记录WHERE

这有可能吗?

4

3 回答 3

2

注意外部表 (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;
于 2012-05-02T16:38:57.100 回答
1

是的!

更改:right outer join_left outer join

select
 u.id, u.fullname,
 r.*
from
 users as u
left 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

左外连接逻辑运算符返回满足第一个(顶部)输入与第二个(底部)输入连接的每一行。它还从第一个输入返回第二个输入中没有匹配行的任何行。第二个输入中的不匹配行作为空值返回。如果 Argument 列中不存在连接谓词,则每一行都是匹配行。

考虑到这一点,这join是有限制的u.id = r.userid。所以,如果where限制不存在,结果将是u.id, u.fullname, r.*万能的users

由于有一个where子句,一些行可能被放在外面,如果你不想要,使用这个查询:

select
 u.id, u.fullname,
 r.*
from
 users as u
left outer join
 rapports as r
on
 u.id = r.userid and u.active = 1
where
 and (r.closed = 0 or CONVERT(varchar, r.periodstart, 112) = convert(varchar, GETDATE(), 112))
order by
 u.fullname
于 2012-05-02T16:27:47.903 回答
-1
SELECT  *
FROM    #temp_table_name

SELECT DISTINCT
        b.NAME ,
        q.valueI
FROM    #temp_table_name q
        RIGHT OUTER JOIN ( SELECT   NAME
                           FROM     ( SELECT    NAME ,
                                                valueI
                                      FROM      #temp_table_name
                                      INTERSECT
                                      SELECT    NAME ,
                                                valueI
                                      FROM      #temp_table_name
                                    ) a
                           GROUP BY a.name
                           HAVING   COUNT(*) = 1
                         ) b ON q.NAME = b.NAME
于 2014-02-03T16:26:18.933 回答