用另一行的值替换查询中的 NULL 值

Replace NULL values in query with values of another row

如何用相同 table 的另一行中的值替换结果集中的所有 null 值? (如回退查询)

示例架构:

CREATE TABLE parent (
    id INTEGER NOT NULL AUTO_INCREMENT,
    int1 INTEGER,
    int2 INTEGER,
    int3 INTEGER,
    PRIMARY KEY (id)
)

查询:

SELECT * FROM table1
WHERE id = ?

但我需要用另一行的值替换所有 null 值。我正在寻找这样的东西:

SELECT * FROM table1 WHERE id = ?
   REPLACE ALL NULL VALUES WITH (
       SELECT * FROM table1 WHERE id = ?
   )

示例:

id    int1    int2   int3
---------------------------
 1     1      null    1
 2     null   null    1
 3     1       4      0

当我首先查询 id 1 和 id 3 作为后备时,我希望结果是:

id    int1   int2   int3
---------------------------
 1     1      4      1

您可以使用 joincoalesce():

select t1.id,
       coalesce(t1.int1, tt1.int1) as int1,
       coalesce(t1.int2, tt1.int2) as int2,
       coalesce(t1.int3, tt1.int3) as int3
from table1 t1 join
     table1 tt1
     on tt1.id = 3
where t1.id = 1;

join 和 ISNULL()(对于 MS SQL 和 IFNULL 对于 MySql)函数将在这种情况下有所帮助:

select t1.id, ISNULL(main.int1, fallback.int1) as int1,
       ISNULL(main.int2, fallback.int2) as int2,
       ISNULL(main.int3, fallback.int3) as int3
from table1 as main join table1 as fallback on fallback.id = 3
where main.id = 1;

看看case

select case mycolumn is null
       when 1 then myothercolumn
       else mycolumn
       end
from mytable

您也可以将 case-when 嵌入另一个。这应该足以解决你的问题。