How to sort an event table by time (have different timezones)?

余生长醉 提交于 2019-12-25 02:44:28

问题


I have a table that is structured the following way (that i can't change):

EventName, LocalTime, Timezone

Data would be something like this:

Event1, 10:00, ET
Event2, 11:00, ET
Event3, 12:00, ET
Event4, 10:00, CT

how can i write a sql to sort this by actual time so result would be like:

Event1, 10:00, ET
Event2, 11:00, ET
Event4, 10:00, CT
Event3, 12:00, ET

Note that Event2 and Event4 happen at the same time so whichever comes first doesn't matter.

My database is MySQL.

Again, I can not modify the source so I have to work with the data I'm dealt with

Thanks


回答1:


Using a modern ver of mysql...

Create table Tz_offsets:
col Timezone, offset
Data:
ET, 0
CT, 1


Select EventName, LocalTime, Timezone
From my_data_table 
JOIN Tz_offsets On Tz_offsets.Timeszone = my_data_table.Timeszone 
Where xxx
Order By (LocalTime - offset)

The key here is that Order By can take an expression.

See http://dev.mysql.com/doc/refman/5.5/en/select.html

Optimization

In the above example, MySql will create a temp table. Depending on the size of your data, it might be much faster to pay a data insertion price vs a data retrieval price.

To do so: add another column to the data table, "time_gmt" and then sort on the new column. But if you can't, the above will work.

If you can't add the Tz_offsets table (if you can only use raw sql), then you have two choices:

  1. Add the Tz_offsets table as a temp table each time you run your sql. Your MySQL user will need temp table create permission.

  2. Do the tz offset lookups within the order by expression by using Case expression.

Eg

Select EventName, LocalTime, Timezone
From my_data_table 
Where xxx
Order By (LocalTime - 
  (CASE Timezone WHEN 'ET' THEN 0 WHEN 'CT' THEN 1 WHEN 'PT' THEN 3 ELSE 0))


来源:https://stackoverflow.com/questions/3252235/how-to-sort-an-event-table-by-time-have-different-timezones

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!