SQL Select Return Default Value If Null

前端 未结 5 1361
伪装坚强ぢ
伪装坚强ぢ 2021-01-01 10:20

Database: MS SQL 2008

SELECT Listing.Title, Listing.MLS, Pictures.PictureTH, Pictures.Picture, Listing.ID 
FROM Listing INNER JOIN Pictures          


        
5条回答
  •  生来不讨喜
    2021-01-01 11:04

    if you want to set the default value if the Pic is null you can do this via COALESCE key word:

    SELECT Listing.Title, Listing.MLS, Pictures.PictureTH, 
    COALESCE (Pictures.Picture, 'default.jpg') AS Pictures, Listing.ID 
    FROM Listing LEFT JOIN Pictures 
    ON Listing.ID = Pictures.ListingID
    WHERE (Pictures.ID = (SELECT MIN(ID) 
    FROM Pictures WHERE (ListingID = Listing.ID)))
    

    You can also achieve this via IsNull like below:

    SELECT Listing.Title, Listing.MLS, Pictures.PictureTH, 
    ISNULL(Pictures.Picture, 'default.jpg') AS Pictures, Listing.ID 
    FROM Listing LEFT JOIN Pictures 
    ON Listing.ID = Pictures.ListingID
    WHERE (Pictures.ID = (SELECT MIN(ID) 
    FROM Pictures WHERE (ListingID = Listing.ID)))
    

    you can read here about IsNull and Coalesce

提交回复
热议问题