2011-10-06 52 views
1

我有充滿類似於2011-10-05 08:09:00.000的時間戳的表,這是通過引用reg_date,mid_date,pre_date的以下查詢來查詢的。我不需要顯示時間戳,而是需要它顯示23 mins ago而不是2011-10-05 08:09:00.000。我嘗試了一些功能,如timediff()format()。我想在查詢中完成這一切,以便我不必查詢和處理結果。自更新MySQL查詢以來的時間

也許我不是很瞭解manaul,但我確信有一種方法可以完成此操作。我對MySQL查詢語句非常陌生。雖然我看到很多潛力和時間節省。我只需要一點點幫助就可以完成任務。

select reg_price as regPrice, _id as ID, lat, lng, reg_date as regDate, 
       mid_date as midDate, pre_date as preDate, 
       format((acos(sin(radians(39.9891)) * sin(radians(lat)) + cos(radians(39.9891)) * 
       cos(radians(lat)) * cos(radians(-82.8116) - radians(lng))) * 6378),1) 
       as distance from stationDetails where (acos(sin(radians(39.9891)) 
       * sin(radians(lat)) + cos(radians(39.9891)) * cos(radians(lat)) * 
       cos(radians(-82.8116) - radians(lng))) * 6378) <= 3 order by reg_price asc, reg_price asc 
+0

以前格式顯示日期時間非常通用 - 沒有一種方法可以做到這一點。你想在幾分鐘內總是?以分鐘/小時爲單位?分鐘/小時/天/月/年?在StackOverflow之後建模?你如何確定何時顯示哪種格式以及如何顯示它? – mellamokb

+0

我不知道您使用的是什麼服務器端語言,但這裏有一個簡單的PHP解決方案:http://www.mdj.us/web-development/php-programming/another-variation-on-the-time-前-php-function-use-mysqls-datetime-field -type/ – mellamokb

+0

它將從服務器上的當前時間確定,因此它可以使用'now()'。我需要它顯示一些像'3天2小時2分鐘23秒'抱歉,不包括在原來的帖子中。 –

回答

0

此功能它的建造時間與SOF類似。

DELIMITER $$ 

DROP FUNCTION IF EXISTS `GetTimeDisplay2` $$ 

CREATE FUNCTION `GetTimeDisplay2` (GivenTimestamp TIMESTAMP) 

RETURNS VARCHAR(32) 

DETERMINISTIC 

BEGIN  

    DECLARE rv VARCHAR(32); 

    DECLARE diff BIGINT;  

    SET diff = UNIX_TIMESTAMP()-UNIX_TIMESTAMP(GivenTimestamp); 

     IF diff < 0 THEN 

     SET rv = CONCAT(abs(diff/60),' From Now'); 

    END IF; 

    IF diff = 0 THEN 

     SET rv = 'Just Now'; 

    END IF; 

    IF diff = 1 THEN 

     SET rv = '1 sec ago'; 

    END IF; 

    IF diff BETWEEN 2 AND 60 THEN 

     SET rv = CONCAT(FORMAT(diff, 0), ' secs ago'); 

    END IF; 

    IF diff BETWEEN 120 AND 3599 THEN 

     SET rv = CONCAT(FORMAT(diff/60, 0), ' mins ago'); 

    END IF; 

    IF diff BETWEEN 61 AND 119 THEN 

     SET rv = CONCAT(FORMAT(diff/60, 0), ' min ago'); 

    END IF; 

    IF diff = 3600 THEN 

     SET rv = CONCAT(FORMAT(diff/3600, 0), ' hr ago'); 

    END IF; 

    IF diff BETWEEN 3601 AND 86399 THEN 

     SET rv = CONCAT(FORMAT(diff/3600, 0), ' hrs ago'); 

    END IF; 

    IF diff > 86400 THEN 

     SET rv = DATE_FORMAT(GivenTimestamp, '%a %l:%i %p'); 

    END IF; 

    IF diff > 259200 THEN 

     SET rv = DATE_FORMAT(GivenTimestamp, '%b %e at %l:%i %p'); 

    END IF; 

    RETURN rv; 

END $$ 

DELIMITER ; 
1

使用TIMEDIFF()TIME_FORMAT()你應該能夠顯示像X分鐘前的結果。它應該很容易根據需要修改這個對其他的時間值,這取決於你想如何處理不同時間尺度(小時,天等):

select 
    TIME_FORMAT(
     TIMEDIFF(now(), dt) 
     ,'%i minute(s) ago' 
    ) 
from Data; 

演示:http://sqlize.com/r1mlXcM62V