来自两个表的SQLite查询 - 选择要返回的值

时间:2013-02-05 20:49:36

标签: sql sqlite

我有两张表,例如

表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的值不为null(如果它们存在)。结果应如下所示:

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

1 个答案:

答案 0 :(得分: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