2014-06-28 80 views
0

我有兩列DATETIME,我想將它們的差別顯示爲'yyyy-mm-dd hh:MM:ss'。我的假設是間隔永遠不會變負。在MySQL中格式化時間間隔爲'yyyy-mm-dd hh:MM:ss'

我的搜索導致:

SELECT CONCAT(DATEDIFF(`to`, `from`), " ", TIMEDIFF(`to`, `from`)) 

但它給出了:

0 00:00:00 

但我希望能得到:

0000-00-00 00:00:00 

有沒有人有什麼建議?

+0

鑑於DATEDIFF返回一個整數,沒有辦法可以轉換爲年/月/日 - 它將取決於開始日期(30天可能是1個月,或者它可能不是......)您是否必須在SQL中執行此操作?如果你可以做到客戶端,它會更簡單。 –

+0

不幸的是我正在尋找一個只有SQL的解決方案。否則它會很容易。我正在編寫一個SQL文件並將其提供給'mysql <./ format.sql'控制檯應用程序,並且它應該按照要求顯示它。 – Mehran

+0

@Mehran檢查我更新的答案 – Sadikhasan

回答

1

可以與TIMESTAMPDIFF重複調用和TIMESTAMPADD計算間隔:

實施例:

SET @to = CAST('2014-10-03 12:00:00' AS DATETIME); 
SET @from = CAST('2011-05-12 13:12:44' AS DATETIME); 

-- get the full years 
SELECT TIMESTAMPDIFF(YEAR, @from, @to); -- 3 
-- get the months, without full years in between 
SELECT TIMESTAMPDIFF(MONTH, TIMESTAMPADD(YEAR, TIMESTAMPDIFF(YEAR, @from, @to), @from), @to); -- 4 
-- get the days, without all months in between 
SELECT TIMESTAMPDIFF(DAY, TIMESTAMPADD(MONTH, TIMESTAMPDIFF(MONTH, @from, @to), @from), @to); -- 20 
-- get the hours, without all days in between 
SELECT TIMESTAMPDIFF(HOUR, TIMESTAMPADD(DAY, TIMESTAMPDIFF(DAY, @from, @to), @from), @to); -- 22 
-- get the minutes, ... 
SELECT TIMESTAMPDIFF(MINUTE, TIMESTAMPADD(HOUR, TIMESTAMPDIFF(HOUR, @from, @to), @from), @to); -- 22 
-- and the same for the seconds 
SELECT TIMESTAMPDIFF(SECOND, TIMESTAMPADD(MINUTE, TIMESTAMPDIFF(MINUTE, @from, @to), @from), @to); -- 16 

看到它在this fiddle

級聯由這些值的結果是直接的:

SELECT CONCAT(
    LPAD(TIMESTAMPDIFF(YEAR, @from, @to), 4, '0'), 
    '-',  
    LPAD(TIMESTAMPDIFF(
     MONTH, 
     TIMESTAMPADD(YEAR, TIMESTAMPDIFF(YEAR, @from, @to), 
     @from), @to), 2, 0), 
    '-', 
    LPAD(TIMESTAMPDIFF(
     DAY, 
     TIMESTAMPADD(MONTH, TIMESTAMPDIFF(MONTH, @from, @to), 
     @from), @to), 2, 0), 
    ' ', 
    LPAD(TIMESTAMPDIFF(
     HOUR, 
     TIMESTAMPADD(DAY, TIMESTAMPDIFF(DAY, @from, @to), 
     @from), @to), 2, 0), 
    ':', 
LPAD(TIMESTAMPDIFF(
     MINUTE, 
     TIMESTAMPADD(HOUR, TIMESTAMPDIFF(HOUR, @from, @to), 
     @from), @to), 2, 0), 
    ':', 
    LPAD(TIMESTAMPDIFF(
     SECOND, 
     TIMESTAMPADD(MINUTE, TIMESTAMPDIFF(MINUTE, @from, @to), 
     @from), @to), 2, 0) 
); 
-- result: 0003-04-20 22:47:16 

看它工作在this fiddle。 請認爲結果可能很容易就像0001-02-30 01:12:14 ...

+0

謝謝,如果您使用CONCAT一個SELECT和LPAD零將是很好的。僅供將來參考。 – Mehran

+0

@Mehran:這是一個有效的原因。完成。 – VMai

相關問題