从表中获取最新行。找到正确的方法

时间:2015-02-06 14:20:06

标签: mysql group-by grouping

结构简单

CREATE TABLE `payments` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `user_id` INT UNSIGNED NOT NULL,
  `amount` DECIMAL(10,2) NOT NULL,
  `status` TINYINT UNSIGNED NOT NULL,
  `time_status` DATETIME NULL,
  PRIMARY KEY (`id`),
  INDEX `tt_user_id` (`user_id` ASC),
  INDEX `tt_status` (`status` ASC)
);

和三种查询变体

  1. select t1.* from payments t1 inner join (select max(id) maxId from payments where user_id=123) t2 on t2.maxId=t1.id

  2. select * from payments where user_id=123 order by id desc limit 1

  3. select * from payments where id=(select max(id) as id from payments where user_id=123)

  4. 哪种查询更适合从付款表中获取最新行?

0 个答案:

没有答案