如何通过MAX(日期)检索行数据?

时间:2013-08-27 08:05:36

标签: mysql sql date select

有一张桌子:


+---------+--------+---------------------+----------+
| user_id | marker | date                | trans_id |
+---------+--------+---------------------+----------+
|       6 | M      | 2013-08-27 11:45:24 |        5 |
|       6 | MA     | 2013-08-27 11:45:42 |        6 |
|       6 | A      | 2013-08-27 11:45:59 |        7 |
+---------+--------+---------------------+----------+
我测试了查询:
SELECT marker , MAX(date) AS maxdate FROM mytable WHERE user_id =6
但这不合适。 你会怎么写查询? 在此先感谢。

6 个答案:

答案 0 :(得分:5)

这将为您提供每user_id

的最新记录
SELECT  a.*
FROM    tableName a
        INNER JOIN
        (
            SELECT  user_id , MAX(date) date
            FROM    tableName
            GROUP   BY user_ID
        ) b ON a.user_id = b.user_id AND
                a.date = b.date
-- WHERE    a.user_id = 6         ==> if you want for specific user_id only

答案 1 :(得分:2)

这将为您提供每user_id

的最新记录
SELECT
  a.user_id,
  b.marker,
  MAX(a.date) AS maxdate,
  b.trans_id
FROM TableName a
JOIN TableName b
  ON b.date = a.date AND a.user_id = b.user_id
GROUP BY a.user_id
ORDER BY a.date DESC;

MAX()是一个聚合函数,就像SUM()COUNT()一样。这些功能应与GROUP BY结合使用。

答案 2 :(得分:1)

这取决于你想要什么。如果要在表中包含最近的行,则查询为:

SELECT *  
FROM mytable 
WHERE (user_id =6 AND date =(SELECT MAX(date) FROM mytable));

如果您希望按最新日期到最早日期排序的用户列表,则查询为:

SELECT * 
FROM mytable 
WHERE (user_id =6)
ORDER BY date DESC;

如果您希望将用户列表按最近的最旧日期排序,则查询为:

SELECT * 
FROM mytable 
WHERE (user_id =6)
ORDER BY date ASC;

答案 3 :(得分:0)

我的偏好是加入子查询(这是你需要所有条目)

SELECT 
    marker, user_id, maxDate.date AS maxdate
FROM
    mytable as t1 join
    (select max(date) as date
    from mytable as t2
    where t2.user_id = 6
    group by user_id) as maxDate
WHERE
    user_id = 6

答案 4 :(得分:0)

还有这样的方式http://sqlfiddle.com/#!2/8d707/4

SELECT
user_id,
marker,
date,
trans_id
FROM TableName
where user_id=6
having date = (select max(date) from TableName where user_id=6)
limit 1

答案 5 :(得分:0)

尝试做这样的事情。

SELECT marker , date 
FROM mytable 
WHERE user_id =6
ORDER BY date DESC
LIMIT 1;

无需加入或子选择声明。

order by子句将按日期对结果进行排序,然后limit子句将只选择第一行。