Select Statement has Case提供选择值 - SQL Server

时间:2017-12-16 19:59:30

标签: sql-server select case

我想从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

2 个答案:

答案 0 :(得分:0)

为什么不使用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

答案 1 :(得分:-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'