尝试使用CASE WHEN里面的CASE WHEN mysql php?

时间:2016-08-11 17:16:58

标签: php mysql

看看我的代码,我希望在cat =' 1'然后CASE或cat =' 2',然后CASE。帮助,欣赏。



<?php
$test ="SELECT DISTINCT dis from $table WHERE 
              ( 
              CASE When cat='1' THEN (CASE  
                      WHEN val2 ='g' THEN val1 > %d
		      WHEN val2 ='l' THEN val1 < %d
		      ELSE val1 !=%d END) 
     
               When cat='2' THEN (CASE  
                      WHEN val2 ='g' THEN val1 > %d
		      WHEN val2 ='l' THEN val1 < %d
		      ELSE val1 !=%d END)
              ELSE END
               )
			   AND dis IN ('19','20','21')
			   ";
?>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

在一个CASE语句中尝试,看看它是否返回预期结果:

<?php
$test ="SELECT DISTINCT dis from $table 
WHERE CASE 
WHEN cat='1' AND val2 ='g' THEN val1 > %d
WHEN cat='1' AND val2 ='l' THEN val1 < %d
WHEN cat='1' THEN val1 !=%d
WHEN cat='2' AND val2 ='g' THEN val1 > %d
WHEN cat='2' AND val2 ='l' THEN val1 < %d
WHEN cat='2' THEN val1 !=%d
END
AND dis IN ('19','20','21')
";
?>

此外,根据cat = 1 or 2是否有任何差异,您可能会将CASE缩减为:

CASE 
WHEN cat in ('1','2') AND val2 ='g' THEN val1 > %d
WHEN cat in ('1','2') AND val2 ='l' THEN val1 < %d
WHEN cat in ('1','2') THEN val1 !=%d
END