此问题的一个很好的例子是计算生日的剩余天数
我正在使用DateDiff(CURRDATE(),“生日专栏”)功能并获得天差,而且我需要做mod 365。
如果联系人昨天过生日,则Mod 365用于检索364.
DateDiff(CURRDATE(),CURRDATE() - INTERVAL 1 DAY)= -1
MOD(-1,365)= -1
:\有线!
答案 0 :(得分:0)
我找到了解决这个问题的方法
MOD(MOD(负,365)365),365)
USE `test`;
DROP procedure IF EXISTS `get_user_contacts`;
DELIMITER $$
USE `test`$$
CREATE PROCEDURE `test`.`get_user_contacts` (user_id INT(11),lim INT(11))
BEGIN
DECLARE is_user_exist INT(11);
SELECT count(*) INTO is_user_exist FROM users WHERE `users`.`id` = user_id;
IF is_user_exist =1 THEN
SELECT `contacts`.*,MOD(MOD(DATEDIFF(CURDATE(),`contacts`.`birthday` + INTERVAL (EXTRACT(YEAR FROM CURDATE())-EXTRACT(YEAR FROM `contacts`.`birthday`)) YEAR)*(-1),365)+365,365) AS DiffDate FROM contacts
LEFT JOIN contacts_users ON `contacts`.`id` = `contacts_users`.`contact_id`
LEFT JOIN users ON `contacts_users`.`user_id` = `users`.`id` LIMIT lim;
ELSE
SELECT 404 as error_number,'User not found.' as message;
END IF;
END$$
DELIMITER ;
祝你好运!
答案 1 :(得分:0)
如果问题是“直到生日那天”,那么365将无法正确处理闰年。
SELECT @bd := DATE('1992-02-02'); -- for testing previous day
SELECT @bd := DATE('1992-05-02'); -- for testing future day
SELECT DATEDIFF(@bd +
INTERVAL (YEAR(CURDATE()) - YEAR(@bd)) + -- Age or Age+1
(DAYOFYEAR(@bd) < DAYOFYEAR(CURDATE())) -- +1 for earlier this year;
YEAR,
CURDATE());