我想根据以下需要在sql查询中使用if条件 "如果年份字段为空,则不计算年龄,如果已设置,则必须执行 这是我的查询。问题出在哪里?请考虑这种情况 '如果有月份和日期,例如0000-03-12'
SELECT id, name, birth_date, birth_time,
city_native, country_native, sex,
city_current, country_current, image,
if(YEAR(birth_date)='','',YEAR(CURDATE()) - YEAR(birth_date) -
(RIGHT(CURDATE(),5) < RIGHT(birth_date,5)),'') AS age
FROM birth_user u
WHERE <condition>;
答案 0 :(得分:1)
您可以使用IFNULL()检查birth_date是否为空
CASE WHEN IFNULL(birth_date,0)=0 THEN '' ELSE YEAR(CURDATE()) - YEAR(birth_date) END as age
答案 1 :(得分:0)
如果您需要“如果它为空”,为什么要将它与零进行比较?
if(birth_date is null, 0, YEAR(CURDATE()) - ......) AS age
0
有适当的“默认年龄”。
答案 2 :(得分:0)
使用NULL而不是0000
SELECT id, name, birth_date, birth_time,
city_native, country_native, sex,
city_current, country_current, image,
if(birth_date is null,'',YEAR(CURDATE()) - YEAR(birth_date) -
(RIGHT(CURDATE(),5) < RIGHT(birth_date,5)),'') AS age
FROM birth_user u
WHERE " . implode(' AND ', $where);