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

问题描述 投票:0回答:2

我想从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
sql-server select case
2个回答
-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'

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
© www.soinside.com 2019 - 2024. All rights reserved.