如何在两个SELECT语句之间在SQL Server中执行LEFT JOIN?

时间:2011-10-25 14:03:19

标签: sql sql-server-2008 relational-database

我在SQL Server中有两个SELECT语句,如下所示:

(SELECT [UserID] FROM [User])
(SELECT [TailUser], [Weight] FROM [Edge] WHERE [HeadUser] = 5043)

我想在[UserID]属性和[TailUser]属性上的这两个SELECT语句之间执行LEFT JOIN。我希望将第二个查询中的现有记录与第一个查询中的相应记录和缺失记录的NULL值相加。我怎么能这样做?

4 个答案:

答案 0 :(得分:54)

SELECT * FROM 
(SELECT [UserID] FROM [User]) a
LEFT JOIN (SELECT [TailUser], [Weight] FROM [Edge] WHERE [HeadUser] = 5043) b
ON a.UserId = b.TailUser

答案 1 :(得分:3)

SELECT [UserID] FROM [User] u LEFT JOIN (
SELECT [TailUser], [Weight] FROM [Edge] WHERE [HeadUser] = 5043) t on t.TailUser=u.USerID

答案 2 :(得分:1)

select *
from user
left join edge
on user.userid = edge.tailuser
and edge.headuser = 5043

答案 3 :(得分:0)

试试这个:

SELECT user.userID, edge.TailUser, edge.Weight 
FROM user
LEFT JOIN edge ON edge.HeadUser = User.UserID
WHERE edge.HeadUser=5043

OR

AND edge.HeadUser=5043

而不是WHERE clausule。