Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

datetime - Convert BigInt timestamp to a real Date with row aggregation and operations in mySQL

I have a query which takes the last update date (timestamp but as a bigint(20) column) like this:

SELECT a.id_workorder, MAX(b.update_date) AS udpate_date
FROM main_log a, 
(
    SELECT MAX(log_date) AS update_date, log_id 
    FROM log_a
    GROUP BY log_id
    UNION
    SELECT MAX(log_date) AS update_date, log_id 
    FROM log_b
    GROUP BY log_id
)b
WHERE a.id_log = b.log_id
GROUP BY b.log_id

and it returns the last update date (unix timestamp as a bigint(20)) for any kind of log (a or b):

id          last update
-------------------------
1001        1376750476349
1002        1376753690861
1003        1378122801986
1004        1377764414858
1005        1377847226096
...

Now I want to format the return in date format and I naively though I can just format the outside timestamp with FROM_UNIXTIME like this:

SELECT 
    a.id_workorder, 
    FROM_UNIXTIME(MAX(b.update_date)) AS udpate_date
FROM main_log a, 
(
    SELECT MAX(log_date) AS update_date, log_id 
    FROM log_a
    GROUP BY log_id
    UNION
    SELECT MAX(log_date) AS update_date, log_id 
    FROM log_b
    GROUP BY log_id
)b
WHERE a.id_log = b.log_id
GROUP BY b.log_id

but it gives

id          last update
-------------------------
1001        null
1002        null
1003        null
1004        null
1005        null
...

I tried to put the conversion in the inner queries as well but it is the same.

I also tried to find answers on SO, mySQL documentation and Google but did not find why the conversion does not works when I make a group by.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your timestamp is in milliseconds try:

SELECT a.id_workorder, 
FROM_UNIXTIME(MAX(b.update_date/1000)) AS udpate_date
FROM main_log a, ...

(i.e. divide the time by 1000 to get seconds)

mysql> select FROM_UNIXTIME(1376750476349);
+------------------------------+
| FROM_UNIXTIME(1376750476349) |
+------------------------------+
| NULL                         |
+------------------------------+
1 row in set (0.06 sec)

mysql> select FROM_UNIXTIME(1376750476349/1000);
+-----------------------------------+
| FROM_UNIXTIME(1376750476349/1000) |
+-----------------------------------+
| 2013-08-17 15:41:16               |
+-----------------------------------+
1 row in set (0.02 sec)

mysql>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...