数据库连接查询的SQL语句
表一User1 列 UserID,name
表二User2 列 UserID,money
表三Web_user 列UserID,realname
User1和User2记录个数相同,两表的UserID完全对应。Web_user中记录个数少,一部分用户没有realname.
我想显示所有的用户,当没有realname时显示空。
我用的是 select a.UserID,b.money,c.realname from User1 as a,User2 as b,Web_user as c where a.UserID=b.UserID and a.UserID=c.UserID
但显示结果是用户没有全显示,web_user中没有的用户显示不出来。怎样显示所有的用户,当用户没在表Web_user中时realname显示空?
------解决方案--------------------select a.UserID,b.money,c.realname
from User1 as a
join User2 as b on a.UserID=b.UserID
left join Web_user as c on a.UserID=c.UserID
------解决方案--------------------
with cte as(
select a.UserID,b.money
from User1 as a ,User2 as b
where a.UserID=b.UserID
)
select a.UserID,a.money,c.realname
from cte a
left join Web_user as c
on a.UserID=c.UserID
------解决方案-------------------- select a.UserID,b.money,isnull( c.realname,'') as realname from User1 as a inner join User2 as b on a.UserID=b.UserID left join Web_user as c on a.UserID=c.UserID