Mysql 从所有列中选择上次(最近)填充的值

Mysql 从所有列中选择上次(最近)填充的值,mysql,sql,select,Mysql,Sql,Select,我有一张桌子,比如说有描述的桌子: 现在,我需要的是: | c1 | c2 | c3 | ________________________ | c11 | c22 | c33 | 它的意思是:为特定引用的每列插入的最后一个值,在本例中,ID=1 我已经通过了WITH子句的link,但无法理解和使用,另外,由于服务器不支持MySQL 8.0。您可以执行以下操作,以选择每个组的最新非空值 select ID, SUBSTRING_INDEX(group_concat(c

我有一张桌子,比如说有描述的桌子:

现在,我需要的是:

|  c1   |  c2  |  c3   |
________________________
|  c11  |  c22 |  c33  |
它的意思是:为特定引用的每列插入的最后一个值,在本例中,ID=1


我已经通过了WITH子句的link,但无法理解和使用,另外,由于服务器不支持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
编辑 要获得每个列的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

您可能不想使用子字符串\u index/group\u concat的原因有很多。我建议在保留的情况下使用它:

这些值中可能包含逗号,然后您可能需要修改分隔符。 组_concat的内部缓冲区可能溢出。 您可能不希望将非字符串值的类型更改为字符串。 另一种选择值得一提。您可以使用聚合获得每列的最大sno:

select id,
       max(case when c1 is not null then sno end) as c1_sno,
       max(case when c2 is not null then sno end) as c2_sno,
       max(case when c3 is not null then sno end) as c3_sno
from t
group by id;
引入实际值只是使用联接的问题:


如果要筛选特定ID,但子查询中的where除外。

您只有3列,或者列更多?是的,更多列。但每一列的情况都是一样的。我只需要每个列的最近值。但您不需要查找最后插入的值,而是查找最后插入的非空值。是。最后按列插入。最后插入哪一列。在您的示例代码段中,我假设ID为1。因此,首先,它给出所有ID。其次,它给出逗号分隔的值,从最近开始。e、 g.ID-C1-C2-C3 1-c11-c22,c21-c33,c32,31那么子字符串末尾的1是什么。。。语句??您可以添加where子句来限制记录,如from子句之后的where ID=1,也可以在其中看到逗号分隔的列表?在demo fiddle中,您可以看到与您的帖子中定义的完全相同的输出,1是从中选择最新的值colum@VAThomas有关更多信息,请查看文档是的,它起作用了。但是当从获取值的位置获取serialNumber时,它只返回1。例如,如果返回了正确的值,则serialNumber仅为1。是否可以为每列获取序列号?好的,很好。我一次可能会收到多达500个结果。那么性能统计数据是什么呢?另外,一个解释将有助于根据我的情况修改它。实际上,有两个t,我对实际的表名感到困惑。请用表名“table1”修改您的答案。谢谢
select id,
       max(case when c1 is not null then sno end) as c1_sno,
       max(case when c2 is not null then sno end) as c2_sno,
       max(case when c3 is not null then sno end) as c3_sno
from t
group by id;
select id, t1.c1, c2.c2, t3.c3
from (select id,
             max(case when c1 is not null then sno end) as c1_sno,
             max(case when c2 is not null then sno end) as c2_sno,
             max(case when c3 is not null then sno end) as c3_sno
      from t
      group by id
     ) t left join
     t t1
     on t1.c1_sno = t.c1_sno left join
     t t2
     on t2.c2_sno = t.c2_sno left join
     t t3
     on t3.c3_sno = t.c3_sno;