问题
I want to select UserType, UserID, FirstName, LastName, UserName from Users table. if PhotoURL is available from Photos table, I select. If record does not exists (UserType - admin only has record in Photos table), I should send spaces.
The query is below. If you think of better query, please suggest.
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
回答1:
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'
回答2:
Why don't you just use a 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
来源:https://stackoverflow.com/questions/47849473/select-statement-has-case-that-provies-select-value-sql-server