/**有一個需求,要求獲得兩個日期想減的天數,小時數,分鍾數。通過查找資料,於是乎我寫出了如下代碼,來獲得兩個字段。*/ 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';