无法按类别和unixtime desc分组

时间:2015-08-04 12:48:44

标签: mysql sql

我创建了:http://sqlfiddle.com/#!2/7bb44/1

CREATE TABLE if not exists tblA
(
id int(11) NOT NULL auto_increment ,
userid int(255),
 category int(255),
  unixtime int(255),
 PRIMARY KEY (id)
);


INSERT INTO tblA (userid,category,unixtime) VALUES
('1', '1','1438689946'),
('1', '2','1438690005'),
('1', '3','1438690007'),
('5', '1','1438690009'),
('2', '1','1438690005'),
('2', '1','1438690398'),
('1', '2','1438691020'),
('1', '3','1438691028'),
('4', '2','1438690005'),
('2', '3','1438691025'),
('2', '2','1438691020'),
('3', '3','1438691022');

Select * from tblA  group by category order by unixtime  desc;

但是我得到了错误的值。这些值不包含正确的unixtime desc。我怎样才能使它工作?我真的很感激任何帮助。

2 个答案:

答案 0 :(得分:1)

你不能以你的方式表达你想要的东西。在 order by之后,group by被处理。大概你想要:

Select a.*
from tblA a join
     (select category, max(unixtime) as maxut
      from tblA
      group by category
     ) c
     on a.category = c.category and a.unixtime = c.maxut
order by a.unixtime desc;

答案 1 :(得分:1)

尝试此查询。如果2个unixtime相同,则只显示1

Select a.*
from tblA a join
     (select category, max(unixtime) as maxut
      from tblA
      group by category
     ) c
     on a.category = c.category and a.unixtime = c.maxut
group by unixtime order by a.unixtime desc;