如何返回连接表中不匹配的所有行以及是否匹配检查条件?

时间:2018-05-23 13:15:18

标签: mysql sql postgresql

如何在

时返回表User的所有行
1. a row has not any match with join table ex **UserDetails**
2. a row has a match in **UserDetails**, check some condition ex: user location is **IND**

示例表

     User
     -----------------------
     id   name
     -----------------------
     1    Hearaman
     2    Ramse
     3    Temmy
     4    Robert

     UserDetails
     -----------------------------
     id   user_id     location
     1    3           USA
     2    4           IND

     Expected results
     --------------------------
     id    name        location
     --------------------------
     1     Hearaman    null
     2     Ramse       null
     4     Robert      IND

1 个答案:

答案 0 :(得分:2)

您可以使用left join并执行过滤器

select u.id, u.name, ud.location
from User u 
left join UserDetails ud on ud.user_id = u.id 
where ud.user_id is null or 
      ud.location = 'IND';