在mysql的where子句中的CASE语句

时间:2014-11-12 12:02:33

标签: mysql case where

我试图从表格中获取数据,我在WHERE子句中使用CASE条件,目前我正在使用以下查询: -

$sQuery = "SELECT SQL_CALC_FOUND_ROWS ".str_replace(" , ", " ", 
implode(", ", $aColumns))." FROM (select CASE when r.agent_id=24
THEN r.Unit ELSE '--' END AS MyUnit, 
CASE when r.agent_id=24 THEN r.landlord_name ELSE '--' END AS landlord_name_new, 
r.*,l.loc_name as location,sl.sub_sub_loc as sub_location,
c.category as   category,CONCAT(u.first_name, ' ', u.last_name) As agent
from crm_sales r 
LEFT JOIN crm_location l ON r.area_location_id=l.loc_id
LEFT JOIN crm_subloc sl ON sl.sub_loc_id = r.sub_area_location_id
LEFT JOIN crm_category c on c.id = r.category_id
LEFT JOIN crm_users u on u.id=r.agent_id
where r.is_active=1 AND r.is_archive=0

AND CASE agent_id WHEN r.agent_id!=24 then r.status=2 else 1=1

 group by r.ref) sel
$sWhere
$sOrder
$sLimit
";

现在我想再增加一个条件,就像这样。

IF(r.agent_id!= 24)那么r.status = 2

已编辑:添加我想要的案例,但错误

1 个答案:

答案 0 :(得分:1)

将WHERE子句中的case / when子句修复为...

AND CASE WHEN r.agent_id != 24 
         then r.status = 2 
         else 1 = 1 end