7

这是我的表结构 -

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 |
-----------------------------------------------------

我想清楚地选择所有user1COURSE_ID数据(连同它的日期)。由于两个相同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
)

但它只选择一排。我该如何纠正?

4

2 回答 2

22

试试这个查询

如果您只想user1使用此查询:

select username, course_id, max(ldate) as date
from tbl 
where username='user1'
group by username, course_id

SQL 小提琴

| 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也将包括

| USERNAME | COURSE_ID |       DATE |
-------------------------------------
|    user1 |        22 | 2013-06-03 |
|    user1 |        54 | 2013-06-03 |
|    user2 |        71 | 2013-06-04 |
于 2013-06-07T08:08:23.990 回答
3

您可以使用MAX

SELECT  COURSE_ID
    , MAX(LDATE) AS LDATE
    FROM COURSE_LOG
    WHERE USERNAME = 'user1'
    GROUP BY COURSE_ID;
于 2013-06-07T08:09:35.817 回答