ORDER BYdate和时间BEFORE GROUP BY名称在MySQL中

我有一个这样的桌子:

name date time tom | 2011-07-04 | 01:09:52 tom | 2011-07-04 | 01:09:52 mad | 2011-07-04 | 02:10:53 mad | 2009-06-03 | 00:01:01 

我想要最早的名字:

 SELECT * ORDER BY date ASC, time ASC GROUP BY name 

( – >不起作用!)

现在它应该让我先疯狂(有更早的date)然后汤姆

但与GROUP BY name ORDER BY date ASC, time ASC给我更新的疯狂第一,因为它分组之前!

再次:问题是,我不能按date和时间sorting,因为GROUP BY必须在ORDER BY之前!

另一种方法:

 SELECT * FROM ( SELECT * ORDER BY date ASC, time ASC ) AS sub GROUP BY name 

GROUP BY组对它命中的第一个匹配结果进行分组。 如果第一次匹配碰巧碰巧是你想要的,那么一切都应该按照预期工作。

我更喜欢这种方法,因为子查询是合乎逻辑的,而不是用其他条件来处理它。

我想这是你正在寻找的:

 SELECT name, min(date) FROM myTable GROUP BY name ORDER BY min(date) 

那时候,你必须通过STR_TO_DATE创build一个mysqldate:

 STR_TO_DATE(date + ' ' + time, '%Y-%m-%d %h:%i:%s') 

所以:

 SELECT name, min(STR_TO_DATE(date + ' ' + time, '%Y-%m-%d %h:%i:%s')) FROM myTable GROUP BY name ORDER BY min(STR_TO_DATE(date + ' ' + time, '%Y-%m-%d %h:%i:%s')) 

由于我不能评论user1908688的答案,所以在这里给MariaDB用户一个提示:

 SELECT * FROM ( SELECT * ORDER BY date ASC, time ASC LIMIT 18446744073709551615 ) AS sub GROUP BY sub.name 

https://mariadb.com/kb/en/mariadb/why-is-order-by-in-a-from-subquery-ignored/

使用子查询:

 select name, date, time from mytable main where date + time = (select min(date + time) from mytable where name = main.mytable) order by date + time; 

这对我工作:

 SELECT * FROM your_table WHERE id IN ( SELECT MAX(id) FROM your_table GROUP BY name ); 

我在这个问题上有一个不同的变化,我只有一个单一的DATETIME字段,并需要一个group by后或根据datetime字段降序sorting后distinctlimit ,但这是什么帮助我:

 select distinct (column) from (select column from database.table order by date_column DESC) as hist limit 10 

在这个例子中,如果你可以对一个concat进行sorting,那么你也许可以用类似的方法逃脱:

 select name,date,time from (select name from table order by concat(date,' ',time) ASC) as sorted 

那么如果你想限制你只是简单地添加你的限制声明到最后:

 select name,date,time from (select name from table order by concat(date,' ',time) ASC) as sorted limit 10