如何从MySQL表中获取正确日期的价格

时间:2015-05-31 04:51:25

标签: mysql

我有以下MySQL表:

---+-------+------------+----------
id | price | e_date     | item_name
---+-------+------------+----------
 1 | 1000  | 2015-01-01 | pen
 2 | 1050  | 2015-02-01 | pen
 3 | 800   | 2015-03-01 | pen
 4 | 850   | 2015-03-20 | pen
 5 | 1150  | 2015-04-01 | pen
 6 | 500   | 2015-01-01 | pencil
 7 | 550   | 2015-02-01 | pencil
 8 | 700   | 2015-03-01 | pencil
---+-------+------------+----------

我想得到不同日子的价格。 假设我想获得2015-02-15的价格,那么价格将为1050。 我希望得到2015-03-15的价格,然后价格为800

我使用了以下查询:

SELECT max(price) FROM table_name WHERE e_date<$date

此处$date来自用户输入(假设用户输入2015-03-15)。

但是,当使用max时,价格将在1050 2015-03-15上返回,800应为name

如何通过单个查询获得合适的价格而不使用子查询(如果可能)?

2 个答案:

答案 0 :(得分:2)

试试这个:

select price
from table_name
where e_date <= $user_date
order by e_date desc
limit 1;

如果您有e_date和price的索引,那么您的查询甚至不需要点击该表。

在提供日期之前或之前获得最高价格

select price
from table_name
where e_date <= $user_date
order by e_date desc, price desc
limit 1;

上述查询按日期和价格对当前日期之前的所有记录进行排序。如果user_date是2015-02-15并且有多个产品,则查询将按日期和价格对所有数据进行排序,并选择最接近的日期和最高价格秒。这可能会也可能不适合您的努力。

在当月获得最高价格

select price
from table_name
where e_date between date_format($user_date,'%Y-%m-01') and $user_date
order by price desc
limit 1;

此查询从月初到用户提供的日期之间提取所有记录。然后它按照最高价格排序,并显示最高价格。

按当月的项目获得最高价格

select item_name, max(price) as max_price
from table_name
where e_date between date_format($user_date,'%Y-%m-01') and $user_date
group by item_name
order by max_price;

示例:http://sqlfiddle.com/#!9/8ce19/9

获取最接近日期的价格(之前或之后)

select price from
(
  (select *, datediff($user_date, e_date) as days 
  from table_name where e_date <= $user_date
  order by e_date desc, price desc
  limit 1)
  union
  (select *, datediff(e_date, $user_date) as days 
  from table_name where e_date >= $user_date
  order by e_date, price desc
  limit 1)
) closest
order by days, price desc
limit 1;

在上面的查询中,我们在日期之前找到1条记录,在给定日期之后找到1条记录。我们计算最近日期的日期和报告价格之间的天数。如果有两个最接近的日子,我们还会按价格排序。

替代版本:

select price
from test
order by abs(datediff(e_date, '2015-02-15')), price desc
limit 1;

示例:http://sqlfiddle.com/#!9/8ce19/19http://sqlfiddle.com/#!9/8ce19/21

答案 1 :(得分:0)

最好的方法是使用年份和月份进行查询,如下所示:

SELECT max(price) 
FROM table_name 
WHERE YEAR(e_date) = $year AND MONTH(e_date) = $month 
group by YEAR(e_date), MONTH(e_date);

或者您可以使用:

SELECT max(price) 
FROM table_name 
WHERE YEAR(e_date) = YEAR($date) AND MONTH(e_date) = MONTH($date) 
group by YEAR(e_date), MONTH(e_date);