1、多表联合查询,主表User~从表UserAddress(一对多关系),重复记录只保留1条(id最小或最大)
(1)查询子表,过滤重复记录
select * from UserAddress a
where not exists (select 1 from UserAddress where a.UserID=UserID and id<a.id)
-这里的 id<a.id 表示对符合条件 a.UserID=UserID记录 进行比较,
例如这里符合条件的id有 1, 3, 5, 6, 13,当用小于"<"比较,最小为1,当ID为1时查询结果为空,
即主表id=1时 where not exists ( ...) 返回真
-如果 id>a.id 用大于号">"比较,最大为13,当ID为13时没有任何数比它更大,查询结果为空,
即主表id=13时 where not exists ( ...) 返回真
(2)联合查询主、从表,过滤重复记录
select User.id, UA.addTel, UA.addCountry, UA.addAddressLine1 from [User] left join
(select UserID, addtel, addCountry, addAddressLine1 from UserAddress a
where not exists (select 1 from UserAddress where a.UserID=UserID and id<a.id)) as UA
ON User.id=UA.UserID