SQL只有在另一个表中不存在时才从表中获取数据

时间:2017-02-23 07:39:24

标签: c# sql sql-server

假设我们有一个表Users来存储有关用户的基本信息

    UserId  FirstName   LastName
    1       Maria       Anders
    2       Ana         Trujillo
    3       Antonio     Moreno
    4       Thomas      Hardy
    5       Christina   Berglund
    6       Hanna       Moos
    7       Frédérique  Citeaux
    8       Martín      Sommer

我们有两个表DetailsException,用于存储有关用户的其他详细信息,实际上两个表都具有相同的结构

Details

UserId  Age
1       10
2       10
3       10
4       40
5       50
6       60
7       70
8       80

Excpetions

UserId  Age
 1      100
 2      100
 3      100

我想编写查询以从Exceptionsdetails获取有关用户的所有详细信息,如果用户的信息存储在exceptions表中,则应覆盖details表中存储的数据1}}表以其他方式从details表中获取数据 所以结果应该是

UserId  FirstName   LastName    Age
1       Maria         Anders    100
2       Ana         Trujillo    100
3       Antonio       Moreno    100
4       Thomas         Hardy    40
5       Christina    Berglund   50
6       Hanna           Moos    60
7       Frédérique    Citeaux   70
8       Martín        Sommer    80

所以在这个例子中,Maria,Ana和Antonio与Ids 1,2,3在details表中的年龄为10岁但是因为他们的数据存储在excpetions表中,结果应该显示为100岁,其他用户没有excpetion表中的信息,所以我们只是从details表中获取数据。

实际上,我提出了一个解决方案,但我认为我可以编写更好的查询,这是我的解决方案

select u.UserId, u.FirstName , u.LastName , e.Age from Exceptions e

inner join Users u on u.UserId = e.UserId

union select  u.UserId, u.FirstName , u.LastName , d.Age from Details d

inner join Users u on u.UserId = d.UserId

where d.UserId not in ( select UserId from Exceptions )

有没有办法避免这个子查询?我们可以做得更好吗?

2 个答案:

答案 0 :(得分:4)

您可以使用左连接的piar和CASE WHEN(或检查null)

select 
   u.UserId
 , u.FirstName 
 , u.LastName 
 , CASE WHEN e.Age IS NOT NULL  then e.age ELSE d.age END  as AGE
from Users u 
left join Details as d on .UserId = d.UserId 
left join Exceptions e on e.UserId = u.UserId

答案 1 :(得分:2)

我没有使用CASE语句,而是使用COALESCE。

select 
   u.UserId
 , u.FirstName 
 ,COALESCE(e.Age,d.age) AGE
from Users u 
left join Details as d on u.UserId = d.UserId 
left join Exceptions e on e.UserId = u.UserId
相关问题