mysql 中兩個日期相減獲得 天 小時 分鐘 或者 小時:分鐘的格式
阿新 • • 發佈:2020-12-28
/**有一個需求,要求獲得兩個日期想減的天數,小時數,分鐘數。通過查詢資料,於是乎我寫出瞭如下程式碼,來獲得兩個欄位。*/ IFNULL(CONCAT( IF(aib.`forecast_reply_time`-aib.`actual_reply_time` < 0,'-',''), IF(FLOOR(HOUR(TIMEDIFF(aib.`forecast_reply_time`,aib.`actual_reply_time`)) / 24)=0,'', CONCAT(FLOOR(HOUR(TIMEDIFF(aib.`forecast_reply_time`,aib.`actual_reply_time`)) / 24),'天')), IF(MOD(HOUR(TIMEDIFF(aib.`forecast_reply_time`,aib.`actual_reply_time`)), 24)=0,'',CONCAT(MOD(HOUR(TIMEDIFF(aib.`forecast_reply_time`,aib.`actual_reply_time`)), 24), '小時')), IF(MINUTE(TIMEDIFF(aib.`forecast_reply_time`,aib.`actual_reply_time`))=0,'0',CONCAT(MINUTE(TIMEDIFF(aib.`forecast_reply_time`,aib.`actual_reply_time`)), '分鐘'))),"") AS stipulatedOften, IFNULL(CONCAT( IF(FLOOR(HOUR(TIMEDIFF(aib.`created_at`,aib.`actual_reply_time`)) / 24)=0,'', CONCAT(FLOOR(HOUR(TIMEDIFF(aib.`created_at`,aib.`actual_reply_time`)) / 24),'天')), IF(MOD(HOUR(TIMEDIFF(aib.`created_at`,aib.`actual_reply_time`)), 24)=0,'',CONCAT(MOD(HOUR(TIMEDIFF(aib.`created_at`,aib.`actual_reply_time`)), 24), '小時')), IF(MINUTE(TIMEDIFF(aib.`created_at`,aib.`actual_reply_time`))=0,'0',CONCAT(MINUTE(TIMEDIFF(aib.`created_at`,aib.`actual_reply_time`)), '分鐘'))),"") AS actualOften,
/**後來需求改變,使用者覺得現實中文的天,小時,分鐘太麻煩了,想要總共的小時數、分鐘數,但是mysql的TIMEDIFF的方法,是精確到秒的,但是使用者又不想要秒。於是乎我又一次進行了更改,使用到了mysql的LEFT函式和LENGTH函式進行了處理弄成了使用者想要的樣子*/ IFNULL(LEFT(TIMEDIFF(aib.`forecast_reply_time`,aib.`actual_reply_time`),LENGTH(TIMEDIFF(aib.`forecast_reply_time`,aib.`actual_reply_time`))-3),"") AS stipulatedOften, IFNULL(LEFT(TIMEDIFF(aib.`actual_reply_time`,aib.`created_at`),LENGTH(TIMEDIFF(aib.`actual_reply_time`,aib.`created_at`))-3),"") AS actualOften,
IF 表示式 IF( expr1 , expr2 , expr3 ) expr1 的值為 TRUE,則返回值為 expr2 expr1 的值為FALSE,則返回值為 expr3
一般我們在使用ifnull()方法的時候,都是類似下面的語句: IFNULL(expr1,expr2) 如果expr1不是NULL,IFNULL()返回expr1,否則它返回expr2。IFNULL()返回一個數字或字串值 select ifnull(name,'no name') from person; 將查詢到的結果中的null轉化為指定的字串,但是其實在where查詢部分也可以使用ifnull(): select * from person where ifnull(name,'no name')='no name';