【问题标题】:How to order tables in SQL by date [closed]如何按日期在 SQL 中对表进行排序 [关闭]
【发布时间】:2013-12-18 11:25:46
【问题描述】:

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

【问题讨论】:

  • 没有样本数据和所需的输出,我很确定我不明白你的意思。
  • 您是否要求对表格中的数据进行排序?按日期?但所有行日期都相同?
  • 如果我理解正确,您希望表名按其中的数据排序。好吧。如果这是真的,这是一个有点奇怪的要求。您最好在设计数据库时多花点心思,这样您就不必通过表来了解数据的位置。
  • 你需要标准化你的数据。
  • 如果你不知道规范化是什么意思,我听说过这本书的好东西,数据库设计为凡人。

标签: mysql sql sorting date


【解决方案1】:

你可以这样做:

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

【讨论】:

  • 正在工作,但我的表格已排序,但我重复了例如:table1,table1,table2,table2,table2...,它们按日期排序,但您知道如何获取他们没有重复:table1,table2 ...
  • @zeka 。 . .此查询应该为每个表返回一行。如果您有重复项,那么您可能会在 from 子句中多次重复一个表。或者,您可能遗漏了max()
  • 一个表中的所有日期都是相同的,所以你需要在每个内部SELECT 'table1' ...语句中添加LIMIT 1或在表名周围添加DISTINCT,这样它就是SELECT DISTINCT(tablename), thedate FROM...
  • @Gordon Linoff ouu 是的,我的错,tnx Gordon
  • @Matt 。 . .我实际上更喜欢你的方法,只是编辑了问题以使用它。第一个工作不需要limit 1,但它会使查询运行得更快。
猜你喜欢
  • 2015-02-27
  • 1970-01-01
  • 2021-02-26
  • 2021-10-17
  • 1970-01-01
  • 1970-01-01
  • 2015-09-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多