Max()+ group在mysql中没有按预期工作

时间:2016-10-02 03:44:29

标签: mysql sql

CREATE TABLE IF NOT EXISTS `order_order_status` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `order_status_id` int(11) NOT NULL,
  `order_id` int(11) NOT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `order_order_status_order_status_id_index` (`order_status_id`),
  KEY `order_order_status_order_id_index` (`order_id`),
  KEY `order_order_status_created_at_index` (`created_at`),
  KEY `order_order_status_updated_at_index` (`updated_at`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=5 ;

--
-- Dumping data for table `order_order_status`
--

INSERT INTO `order_order_status` (`id`, `order_status_id`, `order_id`, `created_at`, `updated_at`) VALUES
(1, 2, 1, '2016-10-01 01:57:37', '2016-10-01 01:57:37'),
(2, 2, 2, '2016-10-01 01:57:54', '2016-10-01 01:57:54'),
(3, 2, 3, '2016-10-02 02:12:49', '2016-10-02 02:12:49'),
(4, 6, 3, '2016-10-02 02:14:19', '2016-10-02 02:14:19');

我想选择的是:

1, 2, 1, '2016-10-01 01:57:37', '2016-10-01 01:57:37'
2, 2, 2, '2016-10-01 01:57:54', '2016-10-01 01:57:54'
4, 6, 3, '2016-10-02 02:14:19', '2016-10-02 02:14:19'

这是按order_id

分组的order_order_status的最新条目

现在出现了问题:

运行

select *, max(created_at) from `order_order_status` group by `order_order_status`.`order_id`

给我回复:

enter image description here

或在prosa

它返回的不是最新的条目,而是返回旧的order_id 3

2 个答案:

答案 0 :(得分:2)

MySQL正如预期的那样完全。问题是你的期望。

带有select *

group by没有意义。你想获得最大值,做这样的事情:

select oos.*
from order_order_status
where oos.created_at = (select max(oos2.created_at)
                        from order_order_status oos2
                        where oos2.order_id = oos.order_id
                       );

聚合(group by)每组产生一行。诸如max()之类的聚合函数获取列的最大值 - 仅此而已。它只是在一个列上运行。

当您使用select *时,您有一堆不在group by中的列,而不是聚合列的参数。 MySQL允许这种语法(不幸的是 - 很少有其他数据库这样做)。 unaggregated列的值是组中不确定行的任意值。

答案 1 :(得分:0)

按order_id desc使用订单可以解决您的问题

select *, max(created_at) from `order_order_status` group by `order_order_status`.`order_id` order by `order_order_status`.`order_id` desc