首页 > 技术文章 > MySQL中变量为空时不执行where过滤

61007257Steven 2020-07-09 18:00 原文

set @Location_Id = 'a';
set @District_Id = 'b';
set @Category_Id = 'c';

select * 
from table_name
where 1=1 and
if(@Location_Id = '', 0=0, LocationId = @Location_Id)  and
if(@District_Id = '', 0=0, DistrictId = @District_Id)  and
if(@Category_Id = '', 0=0, CategoryId = @Category_Id);

 

推荐阅读