gpt4 book ai didi

php - MySQL中使用条件语句定义变量

转载 作者:行者123 更新时间:2023-11-29 07:51:04 25 4
gpt4 key购买 nike

我有一个表“产品”,其中包含以下列:

| price | discount_price | start_discount | end_discount | ... |

*start_discount 和 end_discount 是 UNIX 时间戳

产品的当前价格取决于时间 - 如果“time()”介于“start_discount”和“end_discount”之间,则当前价格为“discount_price”,否则为“price

我正在尝试返回“current_price”变量。在 PHP 中,我会这样写:

$current_price = (time() > $start_discount && time() < $end_discount)? $discount_price : $price;

如何在不涉及 PHP 的情况下在 MySQL 中实现与上述相同的效果?

到目前为止我有这个:

SELECT *, (**price OR discount_price**) as current_price FROM products WHERE active = 1 AND current_price BETWEEN '100' AND '200' ORDER BY current_price;

最佳答案

这里有一个方法,我只是选择价格,你可以从表中选择你想要的任何内容

select
case when
now() > start_discount AND now() < end_discount then discount_price
else price end as current_price
from
products
WHERE
active = 1
AND price BETWEEN '100' AND '200'
ORDER BY current_price

编辑:刚刚注意到您在 where 条件中使用 current_price ,但您不能这样做,因为它是别名,因此您可能需要在 where 子句中使用表列或使用 having子句为

select
case when
now() > start_discount AND now() < end_discount then discount_price
else price end as current_price
from
products
WHERE
active = 1
having current_price BETWEEN '100' AND '200'
ORDER BY current_price

这是我做的测试

mysql> create table products (price int, discount_price int ,start_discount date ,end_discount date);
Query OK, 0 rows affected (0.08 sec)

mysql> insert into products values (100,60,'2014-10-01','2014-11-01'),(200,160,'2014-10-01','2014-10-10'),(300,200,'2014-11-01','2014-11-15');
Query OK, 3 rows affected (0.00 sec)
Records: 3 Duplicates: 0 Warnings: 0

mysql> select case when now() > start_discount AND now() < end_discount then discount_price else price end as current_price from products order by current_price;
+---------------+
| current_price |
+---------------+
| 60 |
| 200 |
| 300 |
+---------------+
3 rows in set (0.00 sec)

关于php - MySQL中使用条件语句定义变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26425537/

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