Select Statement has Case that provies select value - SQL Server

て烟熏妆下的殇ゞ 提交于 2019-12-24 20:58:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!