我想从Users表中选择UserType,UserID,FirstName,LastName,UserName。如果照片表中有PhotoURL,我选择。如果记录不存在(UserType - admin仅在Photos表中有记录),我应该发送空格。
查询如下。如果您考虑更好的查询,请建议。
Select UserType, UserID, FirstName, LastName, UserName,
CASE
WHEN EXISTS(
SELECT PhotoURL FROM Photos WHERE Photos.UserID = Users.UserID AND UserType = 'admin' AND Photos.PhotoNum = 1
)
THEN (
SELECT PhotoURL FROM Photos WHERE Photos.UserID = Users.UserID AND UserType = 'admin' AND Photos.PhotoNum = 1
)
ELSE ''
END AS PhotoURL
from Users
SELECT UserType, Users.UserID, FirstName, LastName, UserName, ISNULL(Photos.PhotoURL, '') as PhotoURL
FROM Users
LEFT JOIN Photos on Users.UserID = Photos.UserID
AND Photos.PhotoNum = 1
AND Users.UserType = 'admin'
你为什么不用left join
Select UserType, UserID, FirstName, LastName, UserName, ISNULL(P.PhotoURL,'')
from Users U left join Photos P
ON U.UserID = P.UserID
where
U.UserType = 'admin' and
(P.PhotoNum is null OR P.PhotoNum = 1) -- No match in the photos table or if there is a match, PhotoNum should be 1