如何将另一列中的值作为最近日期,而不是null

  • 本文关键字:日期 最近 null 一列 mysql date
  • 更新时间 :
  • 英文 :


我在mysql服务器上有下一个表结构:

person_id   company_id  time_of_registration
12          333         2022-02-15 8:03:00
13          333         2022-02-15 8:04:00
14          NULL        2022-02-15 8:10:00
15          333         2022-02-15 8:10:00
16          NULL        2022-02-15 8:12:30
17          222         2022-02-15 8:14:00
18          NULL        2022-02-15 8:23:00
19          111         2022-02-15 11:04:00

如果company_id列中有null,我想放最近的company_id(按时间_of_registration(。

所需输出为:

person_id   company_id  time_of_registration
12          333         2022-02-15 8:03:00
13          333         2022-02-15 8:04:00
14          333         2022-02-15 8:10:00
15          333         2022-02-15 8:10:00
16          222         2022-02-15 8:12:30
17          222         2022-02-15 8:14:00
18          222         2022-02-15 8:23:00
19          111         2022-02-15 11:04:00

提前谢谢。

您可以使用COALESCE((将值默认为由副作用赋值表达式设置的用户变量。类似以下内容:

SELECT person_id,
@cmp := COALESCE(company_id, @cmp) AS company_id,
FROM MyTable
ORDER BY time_of_registration;

最新更新