开发者

How to use case in where clause

I want to get only status = 1 records. But I don't have status column in my table. So I derived the value using CASE... WHEN... THEN. But when I try to use case in where clause, It shows syntax error.

my query

SELECT SQL_CALC_FOUND_ROWS *,
    CASE
        WHEN quantity > nu开发者_JAVA百科m_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'

How can I do this ?


remove AS STATUS from where clause

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'

But your CASE is really unnecessary. Just use your CASE condition as stand-alone WHEREcondition, like

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


If you do not want to repeat the case statement you could wrap the select in a subselect or make a view. Subselect is something like

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


Nobody Suggested the HAVING Clause?

This allows you to query the selected columns, instead of the actual results. Great for using case and function calls.


I suppose you have some other, more complicated query, as the one you have provided is equivalent to:

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'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜