如何将MySQL变量放入Where子句中

时间:2016-04-21 05:31:31

标签: mysql variables

我在这里查询:

select *,@final := DATE_ADD(start_date, INTERVAL 2 YEAR) AS final_date from emp_employee as emp
where employee_type_id=2
and (end_date is null or end_date>now());


结果是:

enter image description here

但是当我将查询更改为:

select *,@final := DATE_ADD(start_date, INTERVAL 2 YEAR) AS final_date from emp_employee as emp
where employee_type_id=2
and YEAR(@final)=2016
and (end_date is null or end_date>now());

它没有给出任何结果,它是空的。我的查询有什么问题以及如何解决?

1 个答案:

答案 0 :(得分:3)

您可以按以下方式更改查询

select *, DATE_ADD(emp.start_date, INTERVAL 2 YEAR) AS final_date from emp_employee as emp
where emp.employee_type_id=2
and YEAR(DATE_ADD(emp.start_date, INTERVAL 2 YEAR))=2016
and (ISNULL(emp.end_date) or emp.end_date>now());

您必须使用ISNULL函数来检查特定列是否具有NULL值。