Replace Default Null Values Returned From Left Outer Join

后端 未结 3 804
夕颜
夕颜 2020-12-07 19:40

I have a Microsoft SQL Server 2008 query that returns data from three tables using a left outer join. Many times, there is no data in the second and third tables and so I g

相关标签:
3条回答
  • 2020-12-07 20:05

    MySQL

    COALESCE(field, 'default')
    

    For example:

      SELECT
        t.id,
        COALESCE(d.field, 'default')
      FROM
         test t
      LEFT JOIN
         detail d ON t.id = d.item
    

    Also, you can use multiple columns to check their NULL by COALESCE function. For example:

    mysql> SELECT COALESCE(NULL, 1, NULL);
            -> 1
    mysql> SELECT COALESCE(0, 1, NULL);
            -> 0
    mysql> SELECT COALESCE(NULL, NULL, NULL);
            -> NULL
    
    0 讨论(0)
  • 2020-12-07 20:21

    In case of MySQL or SQLite the correct keyword is IFNULL (not ISNULL).

     SELECT iar.Description, 
          IFNULL(iai.Quantity,0) as Quantity, 
          IFNULL(iai.Quantity * rpl.RegularPrice,0) as 'Retail', 
          iar.Compliance 
        FROM InventoryAdjustmentReason iar
        LEFT OUTER JOIN InventoryAdjustmentItem iai  on (iar.Id = iai.InventoryAdjustmentReasonId)
        LEFT OUTER JOIN Item i on (i.Id = iai.ItemId)
        LEFT OUTER JOIN ReportPriceLookup rpl on (rpl.SkuNumber = i.SkuNo)
    WHERE iar.StoreUse = 'yes'
    
    0 讨论(0)
  • 2020-12-07 20:29

    That's as easy as

    IsNull(FieldName, 0)
    

    Or more completely:

    SELECT iar.Description, 
      ISNULL(iai.Quantity,0) as Quantity, 
      ISNULL(iai.Quantity * rpl.RegularPrice,0) as 'Retail', 
      iar.Compliance 
    FROM InventoryAdjustmentReason iar
    LEFT OUTER JOIN InventoryAdjustmentItem iai  on (iar.Id = iai.InventoryAdjustmentReasonId)
    LEFT OUTER JOIN Item i on (i.Id = iai.ItemId)
    LEFT OUTER JOIN ReportPriceLookup rpl on (rpl.SkuNumber = i.SkuNo)
    WHERE iar.StoreUse = 'yes'
    
    0 讨论(0)
提交回复
热议问题