gpt4 book ai didi

mysql - 如何使用 MySQL 覆盖 NULL 值将两行合并为一行?

转载 作者:行者123 更新时间:2023-11-29 11:25:12 24 4
gpt4 key购买 nike

我有两行,如下所示:

id    title            format    region    discs    user_id    origin_id
------------------------------------------------------------------------
1 12 Monkeys DVD NULL NULL NULL NULL
2 Twelve Monkeys NULL NULL 1 2 1

我想要执行一个 SELECT 调用,当 user_id 不为 NULL 时,该调用始终返回数据。这是我正在寻找的结果应该是:

id    title            format    region    discs    user_id   origin_id
-----------------------------------------------------------------------
2 Twelve Monkeys DVD NULL 1 2 1

如您所见,由于 id 2 上的 NULLformat 已从 id 1 填充,但是其他所有内容均从 id 2 开始填充。

可以为我执行此操作的 MySQL 语句是什么?

最佳答案

对于给定的数据,您可以使用左连接coalesce()来确定值的优先级:

select coalesce(t.id, t2.id) as id,
coalesce(t.title, t2.title) as title,
coalesce(t.format, t2.format) as format,
coalesce(t.region, t2.region) as region,
coalesce(t.discs, t2.discs) as discs,
t.user_id
from t left join
t t2
on t2.user_id is null
where t.user_id is not null;

关于mysql - 如何使用 MySQL 覆盖 NULL 值将两行合并为一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38339544/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com