我在数据库中有以下表格。
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<id>copy-mstrweb-jars</id>
<phase>validate</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${project.basedir}/lib</outputDirectory>
<resources>
<resource>
<directory>${build.location}/${version}/java/jar</directory>
<filtering>false</filtering>
<includes>
<include>some.jar</include>
</includes>
</resource>
<resource>
<directory>${build.location}/${version}/jars</directory>
<filtering>false</filtering>
<includes>
<include>somejar.jar</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
如何为每个user_id仅提取按+----+---------+---------------------+-----------+
| id | user_id | timeid | course_id |
+----+---------+---------------------+-----------+
| 02 | 2 | 2016-01-27 19:24:17 | 14 |
| 03 | 2 | 2016-02-27 19:24:27 | 15 |
| 04 | 2 | 2016-03-27 19:24:37 | 16 |
| 05 | 3 | 2016-01-27 19:24:17 | 19 |
| 06 | 3 | 2016-02-27 19:24:27 | 18 |
| 07 | 3 | 2016-03-27 19:24:37 | 17 |
+----+---------+---------------------+-----------+
排序的最新行?
换句话说:
timeid
答案 0 :(得分:2)
一种简单的方法是使用=
和相关的子查询:
select t.*
from t
where t.timeid = (select max(t2.timeid) from t t2 where t2.user_id = t.user_id);
答案 1 :(得分:1)
您可以使用以下查询:
SELECT t1.id, t1.user_id, t1.timeid, t1.course_id
FROM mytable as t1
JOIN (
SELECT user_id, MAX(timeid) AS timeid
FROM mytable
GROUP BY user_id
) AS t2 ON t1.user_id = t2.user_id AND t1.timeid = t2.timeid
t2
是一个派生表,其中包含每timeid
的最新user_id
值。如果您将原始表格加入此表格,则可以取回具有最新每组值的记录的所有字段。
答案 2 :(得分:0)
您可以使用像
这样的mysql查询SELECT id, user_id, timeid, course_id FROM tablename ORDER BY timeid DESC GROUP BY user_id;