gpt4 book ai didi

mysql - 如何在where子句中使用case

转载 作者:可可西里 更新时间:2023-11-01 06:39:15 24 4
gpt4 key购买 nike

我只想获取status = 1 条记录。但是我的表中没有状态列。所以我使用 CASE...WHEN...THEN 推导出值。但是当我尝试在 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'

我该怎么做?

最佳答案

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

关于mysql - 如何在where子句中使用case,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6812276/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com