gpt4 book ai didi

mysql - 如何在 SQL 中按日期对表进行排序

转载 作者:行者123 更新时间:2023-11-30 00:58:40 25 4
gpt4 key购买 nike

我在数据库表中有:table1、table2、table3...所有这些表都有 date_table1、date_table2 列,..这些列的日期对于该表中的所有行都相同,例如,table1 具有 date_table1 列日期为 2013-01-01,并且所有行中都具有相同的日期,table2 将具有例如日期 2013-01-02,并且它将仅具有该日期、该值。因此,我需要按日期对表进行排序,我需要获取从最早日期到最晚日期排序的表名称列表。有人可以帮忙吗?

最佳答案

你可以这样做:

select tablename, thedate
from ((select 'table1' as tablename, max(date) as thedate from table1) union all
(select 'table2' as tablename, max(date) as thedate from table2) union all
(select 'table3' as tablename, max(date) as thedate from table3)
) t
order by thedate, tablename;

要添加更多表,只需使用 union all 添加其他行即可。如果你有很多表,但是Excel中的表名在某一列中,并使用Excel函数生成SQL代码。

编辑:

我实际上更喜欢马特的方法(他在评论中提到):

select tablename, thedate
from ((select 'table1' as tablename, date as thedate from table1 limit 1) union all
(select 'table2' as tablename, date as thedate from table2 limit 1) union all
(select 'table3' as tablename, date as thedate from table3 limit 1)
) t
order by thedate, tablename;

没有 table<n>(date) 上的索引,这会运行得更快。

关于mysql - 如何在 SQL 中按日期对表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20333635/

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