【问题标题】:Replace NULL values in query with values of another row将查询中的 NULL 值替换为另一行的值
【发布时间】:2017-10-11 22:19:11
【问题描述】:

如何将结果集中的所有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

【问题讨论】:

  • CASE 声明对您有帮助吗?
  • 我不知道,这就是我问的原因;)

标签: mysql sql join self-join


【解决方案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;

【讨论】:

    【解决方案2】:

    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;
    

    【讨论】:

    • 据我所知 MySQL 不存在 isnull 。这是一个 MS SQL 函数。
    【解决方案3】:

    看看case

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

    您还可以将case-when 嵌入到另一个中。这应该足以让您解决问题。

    【讨论】:

      猜你喜欢
      • 2022-11-13
      • 2016-11-11
      • 1970-01-01
      • 1970-01-01
      • 2019-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多