我有两个表,例如
表格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'对应的Table1行,但Table2的值不为null(如果存在)。结果应如下所示:
ID | Prop1 | Prop2 | Prop3
--------------------------------
1 | aa | b | c
最佳答案
您可以使用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
关于sql - 从两个表中查询SQLite-选择要返回的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14716642/