0

在这里,我创建了一些表来测试:

CREATE TABLE IF NOT EXISTS `test` (
  `index` varchar(255) NOT NULL,
  `index2` varchar(255) NOT NULL,
  `date` date NOT NULL,
  `somenumber` int(10) NOT NULL,
  PRIMARY KEY (`index`,`index2`,`date`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `test` (`index`, `index2`, `date`, `somenumber`) VALUES
('kevin', 'little', '2013-06-11', 1),
('kevin', 'little', '2013-07-03', 5),
('maria', 'smith', '2013-07-01', 3),
('martin', 'luther', '2013-07-04', 13),
('martin', 'luther', '2013-07-05', 14);

现在我想为大家获取最新 somenumber的,按somenumber DESC. 这是我的尝试:

SELECT * FROM `test` GROUP BY `index`, `index2` ORDER BY `somenumber` DESC

问题是这个查询总是为每个组取一个 somenumber,但它并不总是最新的。

(我知道索引名在这里没有太大意义,但我认为这比使用随机数索引更容易阅读)

4

2 回答 2

3

希望对你有帮助

SELECT * 
FROM  
    (SELECT * FROM `test`  ORDER BY `index`, `date` DESC) as temp
GROUP BY `index`, `index2` 
ORDER BY `somenumber` DESC
于 2013-07-05T09:46:17.650 回答
2

尝试这个:

SELECT t1.`INDEX`, t1.`INDEX2`, t1.`SOMENUMBER` FROM TEST t1 INNER JOIN
(SELECT `INDEX`, `INDEX2`, MAX(`DATE`) DATE FROM TEST
GROUP BY `INDEX`, `INDEX2`) t2 ON t1.INDEX = t2.INDEX AND t1.INDEX2 = t2.INDEX2 AND t1.DATE = t2.DATE
于 2013-07-05T09:41:22.650 回答