这是我的表结构-
TABLE : COURSE_LOG ----------------------------------------------------- | ID | USERNAME | COURSE_ID | LDATE | ----------------------------------------------------- | 1 | user1 | 22 | 2013-06-01 | ----------------------------------------------------- | 2 | user1 | 54 | 2013-06-03 | ----------------------------------------------------- | 3 | user1 | 22 | 2013-06-03 | ----------------------------------------------------- | 4 | user2 | 71 | 2013-06-04 | -----------------------------------------------------
我想清楚地选择所有user1的COURSE_ID数据(以及日期)。由于日期在两个相同的COURSE_ID条目之间会有所不同,因此我想选择日期最近的行。我希望得到这样的结果-
user1
COURSE_ID
----------------------------- | COURSE_ID | LDATE | ----------------------------- | 54 | 2013-06-03 | ----------------------------- | 22 | 2013-06-03 | ----------------------------- | 71 | 2013-06-04 | -----------------------------
我不想要这个-
----------------------------- | 22 | 2013-06-01 | // THIS SHOULD BE OMITTED FROM RESULT BECAUSE THERE ----------------------------- // IS ANOTHER RECENT ENTRY WITH THE SAME COURSE_ID
我正在使用此查询-
SELECT DISTINCT(COURSE_ID), LDATE FROM COURSE_LOG WHERE USERNAME = 'user1' AND LDATE = ( SELECT LDATE FROM COURSE_LOG WHERE USERNAME = 'user1' ORDER BY LDATE DESC LIMIT 1 )
但是它只能挑一排。我该如何纠正?
试试这个查询
如果只想user1使用此查询:
select username, course_id, max(ldate) as date from tbl where username='user1' group by course_id
| USERNAME | COURSE_ID | DATE | ------------------------------------- | user1 | 22 | 2013-06-03 | | user1 | 54 | 2013-06-03 |
如果要查找所有用户的最新日期,请使用此查询
select username, course_id, max(ldate) as date from tbl group by username, course_id
在此查询中,user2还将包含的数据
user2
| USERNAME | COURSE_ID | DATE | ------------------------------------- | user1 | 22 | 2013-06-03 | | user1 | 54 | 2013-06-03 | | user2 | 71 | 2013-06-04 |