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

时间:2014-10-17 12:57:11

标签: php mysql

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

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

* start_discount和end_discount是UNIX时间戳

产品的当前价格取决于时间 - 如果'时间()'介于' start_discount '和' end_discount '之间,那么当前价格为“ discount_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;

2 个答案:

答案 0 :(得分:1)

这是一种方法,我只选择你可以从表格中选择的价格

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子句中使用table列或者使用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)

答案 1 :(得分:1)

您可以使用mySQL中的IF语句执行此操作

select id, name,
  if(startDiscount_at <= now() && endDiscount_at > now(), discountPrice, price) as current_price
from products
  where active = 1
  having current_price between 100 and 200
  order by current_price;

Link to SQLFiddle