gpt4 book ai didi

mysql - 从所有列中选择最后(最近)填充的值

转载 作者:行者123 更新时间:2023-11-29 02:13:11 32 4
gpt4 key购买 nike

我有一张 table ,说 table 的描述为:

| ID | SNO |  c1   |  c2  |  c3   |
___________________________________
| 1 | 1 | c11 | c21 | c31 |
| 1 | 2 | NULL | c22 | c32 |
| 1 | 3 | NULL | NULL | c33 |



现在,我需要的是:

|  c1   |  c2  |  c3   |
________________________
| c11 | c22 | c33 |

这意味着:特定引用的每列的最后插入值,在本例中,ID = 1

我已经经历了this链接,WITH子句,但无法理解和使用,另外,由于服务器不支持MySQL 8.0。

最佳答案

你可以做类似下面的事情来选择每组最新的非空值

select ID,
SUBSTRING_INDEX(group_concat(c1 order by SNO desc),',',1) c1,
SUBSTRING_INDEX(group_concat(c2 order by SNO desc),',',1) c2,
SUBSTRING_INDEX(group_concat(c3 order by SNO desc),',',1) c3
from demo
group by ID

DEMO

编辑

要获取每一列的 SNO,您可以按如下方式更新您的查询

select ID,
substring_index(group_concat(c1 order by SNO desc),',',1) c1,
substring_index(group_concat(case when c1 is not null then SNO end order by SNO desc),',',1) sno1,
substring_index(group_concat(c2 order by SNO desc),',',1) c2,
substring_index(group_concat(case when c2 is not null then SNO end order by SNO desc),',',1) sno2,
substring_index(group_concat(c3 order by SNO desc),',',1) c3,
substring_index(group_concat(case when c3 is not null then SNO end order by SNO desc),',',1) sno3
from demo
where ID = 1
group by ID

DEMO

关于mysql - 从所有列中选择最后(最近)填充的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46261579/

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