繁体   English   中英

如何返回联接表中所有不匹配的行,如果匹配则检查条件?

[英]How to return all the rows which has not match in join table and if it had match check the condition?

何时返回表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

您可以使用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';

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM