SQL Select Return Default Value If Null

前端 未结 5 1359
伪装坚强ぢ
伪装坚强ぢ 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

    0 讨论(0)
  • 2021-01-01 11:19

    Need to do a LEFT join

    SELECT Listing.Title, Listing.MLS, Pictures.PictureTH, Pictures.Picture, Listing.ID 
    FROM Listing LEFT JOIN Pictures ON Listing.ID = Pictures.ListingID
    
    0 讨论(0)
  • 2021-01-01 11:21

    Landmine, what database are you using?

    If it's sql server 2005 or above or oracle, you can use the pivot command to achieve this.

    0 讨论(0)
  • 2021-01-01 11:24

    Two things:

    1. Use left outer join instead of inner join to get all the listings, even with missing pictures.
    2. Use coalesce to apply the default

      SELECT Listing.Title
          , Listing.MLS
          , Pictures.PictureTH
          , coalesce(Pictures.Picture, 'default.jpg') as Picture
          , Listing.ID  
      FROM Listing 
      LEFT OUTER JOIN Pictures 
          ON Listing.ID = Pictures.ListingID 
      

    EDIT To limit to one row:

    SELECT Listing.Title
        , Listing.MLS
        , Pictures.PictureTH
        , coalesce(Pictures.Picture, 'default.jpg') as Picture
        , Listing.ID  
    FROM Listing 
    LEFT OUTER JOIN Pictures 
        ON Listing.ID = Pictures.ListingID 
    WHERE Pictures.ID is null
    OR Pictures.ID = (SELECT MIN(ID) 
        FROM Pictures 
        WHERE (ListingID = Listing.ID))) 
    
    0 讨论(0)
  • 2021-01-01 11:25

    Use left outer join instead of inner join

    Inner join will return results if and only if there is a result that satisfies the join.

    Left outer join will return results from the left side table, and if the join is satisfied also add results from the right side table..

    If you need to convert the null values returned from the non-satisfying joins, then use coalesce function like coalesce(Pictures.Picture, 'default.jpg')

    0 讨论(0)
提交回复
热议问题