2

例如,我有两张桌子

表格1

ID  |  Prop1  |  Prop2  |  Prop3
--------------------------------
 1  |    a    |   b     |   c
 2  |    d    |   e     |   f

表2

Name  |  ID  |  Prop1  |  Prop2
-------------------------------
 i    |   1  |   aa    |  null

我想要做的是返回(不修改)与 Table2.Name = 'i' 的 ID 对应的 Table1 的行,但 Table2 的值不为空(如果它们存在)。结果应如下所示:

ID  |  Prop1  |  Prop2  |  Prop3
--------------------------------
 1  |    aa   |   b     |   c
4

1 回答 1

1

您可以使用IFNULL(x, y)以下值替换NULL

SELECT
    t1.ID
   ,IFNULL(t2.Prop1, t1.Prop1) AS Prop1
   ,IFNULL(t2.Prop2, t1.Prop2) AS Prop2
   ,IFNULL(t2.Prop3, t1.Prop3) AS Prop3
FROM
    Table1 t1
LEFT JOIN
    Table2 t2
    ON
    t1.ID = t2.ID

请注意,IFNULL()只接受两个参数。如果您认为您可能会在某个时候添加更多表格,请切换到COALESCE()

SELECT
    t1.ID
   ,COALESCE(t2.Prop1, t1.Prop1) AS Prop1
   ,COALESCE(t2.Prop2, t1.Prop2) AS Prop2
   ,COALESCE(t2.Prop3, t1.Prop3) AS Prop3
FROM
    Table1 t1
LEFT JOIN
    Table2 t2
    ON
    t1.ID = t2.ID
于 2013-02-05T21:05:25.927 回答