MySQL获取最小,最大和最旧分组

时间:2016-11-21 21:07:31

标签: php mysql

我有一个小项目,我正在进行并进行以下设置:

MariaDB [b7_19195200_prices]> select * from watchlist;
+----+-------------+-------+---------------------+--------+
| id | item        | price | recorded            | errors |
+----+-------------+-------+---------------------+--------+
|  3 | 32725999014 | 1.46  | 2016-11-21 20:30:22 |      0 |
|  4 | 32725999014 | 1.93  | 2016-11-21 20:56:21 |      0 |
|  5 | 32725999014 | 2.01  | 2016-11-21 20:56:32 |      0 |
|  6 |      122444 | 22.43 | 2016-11-21 21:03:19 |      0 |
|  7 | 32725999014 | 1.11  | 2016-11-21 21:25:33 |      0 |
+----+-------------+-------+---------------------+--------+
5 rows in set (0.00 sec)

所以我想获得最高价格,最低价格和第一个(最早记录的那个项目的价格)。所以我得到的结果如下:

+----+-------+-------+-------------+----------+
| id | low   | high  | item        | original | 
+----+-------+-------+-------------+----------+
|  6 | 22.43 | 22.43 |      122444 |    12.11 |
|  3 | 1.11  | 2.01  | 32725999014 |    0.51  |
+----+-------+-------+-------------+----------+

低,高和原价分别是该商品的最低价,最高价和原价。奖金是能够知道它的最高和最低时间。我一直在使用2种不同的查询来获得最高,最低和最低价格:

SELECT `id`, MIN(`price`) low, MAX(`price`) high, `item`
FROM `watchlist`
GROUP BY `item`;

SELECT `id`, MIN(`recorded`), `price` original, `item`
FROM `watchlist`
GROUP BY item;

无论如何我能做到这一点?

谢谢!

1 个答案:

答案 0 :(得分:1)

如果您不需要ID,则可以使用加入

 select t1.*, t2.* 
 from ( 
  SELECT MIN(`price`) low, MAX(`price`) high, `item`
  FROM `watchlist`
  GROUP BY `item`
) t1
left  join (
  SELECT  MIN(`recorded`), `price` original, `item`
  FROM `watchlist`
  GROUP BY item
) t2 on t1.`item` =  t2.`item`

否则,如果您还需要subselect上的id join和tuple

 select t1.*, t2.* 
 from ( 
  SELECT MIN(`price`) low, MAX(`price`) high, `item`
  FROM `watchlist`
  GROUP BY `item`
)  t1
left  join (
  select `id`, `recorded`,  `price`, `item`
  from `watchlist`
  where (  `item`,  `recorded`) in (
        select `item`,  min(`recorded`)
        FROM `watchlist`
        GROUP BY item
  )
) t2 on t1.`item` =  t2.`item`

第二个应该是正确的,因为明确选择行并获得非聚合值的第一个结果