php - Mysql function returns empty result
I tried to create mysql function. For particular month it returning empty result. I need to set that empty result as '0'. How to do this? Here is my mysql function.
DELIMITER $$ CREATE FUNCTION `monthtargetbyuser`(`userId` BIGINT,month VARCHAR(11),year VARCHAR(11)) RETURNS int(11) BEGIN DECLARE target,da BIGINT; set da = year-month; SET target = (SELECT ifnull(user_target.monthly_target,0) as monthly_target from user_target left join users on users.id=user_target.user_id where date_format(users.doj,'%Y-%m') <= 'da' and user_target.year=year and year(users.doj)>0 and users.locked !=1 and users.id =userId ); RETURN target; END
Thanks in Advance!!
set da = year-month;-> year and month are declared as varchars, however, in this context they would be interpreted as integers. If you wanted to create a string such as '2016-05', then use the concat() function:
concat(year,'-',month). I have absolutely no idea why you declared da as bigint. It should be declared as varchar.
date_format(users.doj,'%Y-%m') <= 'da'-> this expression compares a string in year-month format with the string 'da'. Sql is not php, the variable names will not be expanded within a string. So, the expression should be:
date_format(users.doj,'%Y-%m') <= da.
I also believe that you mixed up the order of the tables in the join. You should not really have a target for a user that does not exist.
If there is no such record that would satisfy your query, then the ifnull() function in the select statement will not even run, this is why you get an empty result in certain occasions. (Although how you tested your function is beyond me, given the issues above). Apparently, you expect to have a maximum of one record returned. In this case I suggest to use max() or min() function within the ifnull() because they guarantee to return a value:
SELECT ifnull(max(user_target.monthly_target),0) as monthly_target ...
I found a solution... I made a mistake in concat of year and month. That makes a issue. This is my corrected code.
Thanks a lot. @Shadow