如何在where子句中使用case

时间:2011-07-25 06:01:04

标签: mysql

我想只获得 status = 1 记录。但我的表格中没有状态栏。所以我使用 CASE ... WHEN ......那么来推导出价值。但是当我尝试在where子句中使用case时,它显示语法错误。

我的查询

SELECT SQL_CALC_FOUND_ROWS *,
    CASE
        WHEN quantity > num_used AND (CURDATE() BETWEEN coupon_start_date AND coupon_end_date) THEN '1'
        ELSE '0'
    END AS STATUS
FROM
    table_coupon_code
WHERE
    (CASE
        WHEN quantity > num_used AND (CURDATE() BETWEEN coupon_start_date AND coupon_end_date) THEN '1'
        ELSE '0'
    END AS STATUS) = '1' AND coupon_status <> '2'

我该怎么做?

4 个答案:

答案 0 :(得分:16)

从where子句

中删除AS STATUS
SELECT SQL_CALC_FOUND_ROWS * ,
  CASE WHEN quantity > num_used AND (CURDATE( ) BETWEEN coupon_start_date AND coupon_end_date)
  THEN '1'
  ELSE '0'
  END AS STATUS
FROM table_coupon_code
WHERE 
CASE WHEN quantity > num_used AND (CURDATE( ) BETWEEN coupon_start_date AND coupon_end_date)
  THEN '1'
  ELSE '0'
  END = '1'
AND coupon_status <> '2'

但是你的CASE真的没必要。只需将CASE条件用作独立的WHERE条件,例如

[...]
WHERE quantity > num_used AND
CURDATE( ) BETWEEN coupon_start_date AND coupon_end_date AND
coupon_status <> '2'

答案 1 :(得分:3)

如果您不想重复case语句,可以将select包装在subselect中或创建视图。 子选择类似于

select status 
  from (select case 
          when zip like '4321%' then 1 else 0 end as status
          from adr 
       ) t 
 where status = 1;

答案 2 :(得分:1)

没有人建议使用HAVING条款?

这允许您查询所选列,而不是实际结果。非常适合使用大小写和函数调用。

答案 3 :(得分:0)

我想你有一些其他更复杂的查询,因为你提供的查询相当于:

SELECT SQL_CALC_FOUND_ROWS * ,
       '1' AS STATUS
FROM table_coupon_code
WHERE quantity > num_used
  AND CURDATE() BETWEEN coupon_start_date AND coupon_end_date
  AND coupon_status <> '2'