如何按日期在SQL中排序表

时间:2013-12-02 16:56:44

标签: mysql sql sorting date

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

1 个答案:

答案 0 :(得分:0)

您可以这样做:

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)上的索引,这将运行得更快。