如何根据字段“time”中的值添加新列

时间:2014-11-06 14:06:41

标签: mysql

我有桌子:

+--------+--------------+-----------+   
| person |.....DAY......| ....hours |  
| Name1 ....2014-01-08... 03:53:23  |   
| Name2 ....2014-01-08... 05:30:54  |  
+--------|--------------|-----------+

如何根据时间字段中的值添加新列label? 如果时间从05:00:00到11:00:00,则值为'1',否则为'0'。看起来应该是这样的:

+---------+--------------+-----------+---------+  
| person  |.....DAY......| ..hours  |  label   |   
| Name1 ....2014-01-08... 03:53:23  |  0 ......|   
| Name2 ....2014-01-08... 05:30:54  |  1.......|   
+---------+--------------+----------+----------+

2 个答案:

答案 0 :(得分:3)

你可以使用这样的东西

update table set label = case when hour(hours) between 5 and 10 then 0 else 1 end;

答案 1 :(得分:1)

由于这是一个计算列,您可以在查询中即时生成

SELECT person, 
       DATE( dt ) AS DAY , 
       case when hour(from_unixtime(sec_to_time(SUM( IF( source LIKE '%вход' OR source LIKE '%въезд', -1, 1 ) * UNIX_TIMESTAMP( dt ) )))) between 5 and 11 
            then 1
            else 0 
       end AS hours
from your_table