我试图使用group by和order by显示表中的最新更新记录

时间:2014-11-15 10:39:35

标签: mysql

我正在尝试使用group by和order by显示表中的最新更新记录,但是它显示的第一个插入值未上次更新。我尝试过,但它没有显示最后更新的值,请尝试解决此查询。

数据库

CREATE TABLE IF NOT EXISTS `stock_maintenance` (
  `sid` int(255) NOT NULL AUTO_INCREMENT,
  `prodid` int(255) NOT NULL,
  `stock` int(255) NOT NULL,
  `stock_date` date NOT NULL,
  PRIMARY KEY (`sid`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=35 ;

INSERT INTO `stock_maintenance` (`sid`, `prodid`, `stock`, `stock_date`) VALUES
(2, 34, 133, '2014-11-02'),
(3, 34, 267, '2014-11-05'),
(5, 35, 12, '2014-11-02'),
(24, 35, 10, '2014-11-04'),
(26, 35, 167, '2014-11-05'),
(27, 34, 167, '2014-11-08'),
(28, 34, 163, '2014-11-16'),
(29, 35, 163, '2014-11-15');

我的Sql查询

SELECT * FROM stock_maintenance group by prodid order by stock_date 

3 个答案:

答案 0 :(得分:2)

您可以使用inner join子查询来实现此目的:

SELECT sm.* 
FROM stock_maintenance sm 
INNER JOIN (
    SELECT prodid, MAX(stock_date) AS stock_date
    FROM stock_maintenance GROUP BY prodid
) AS max USING (prodid, stock_date);

结果是:

'28', '34', '163', '2014-11-16'
'29', '35', '163', '2014-11-15'

答案 1 :(得分:-1)

MySQL中的默认排序顺序是ASC(升序),表示从最低到最高。因此,您的查询将从最低(最早)日期到最高(最晚)日期进行排序。

因此,要首先获取最新记录,您可以将查询更改为:

SELECT * FROM stock_maintenance group by prodid order by stock_date DESC

更新

SELECT * FROM
    (SELECT * FROM stock_maintenance ORDER BY stock_date DESC)
    AS sm GROUP BY prodid

答案 2 :(得分:-1)

您可以通过首先运行子选择查询来排序结果,然后按分组来实现此目的。

SELECT * FROM (select * from stock_maintenance order by stock_date desc) as temp_table group by prodid order by stock_date ;

+-----+--------+-------+------------+
| sid | prodid | stock | stock_date |
+-----+--------+-------+------------+
|  29 |     35 |   163 | 2014-11-15 |
|  28 |     34 |   163 | 2014-11-16 |
+-----+--------+-------+------------+