1

这里有张桌子:


+---------+--------+---------------------+----------+
| 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
但它不正确。您将如何编写查询?提前致谢。

4

6 回答 6

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
于 2013-08-27T08:07:35.287 回答
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()and一样COUNT()。这些功能应与GROUP BY.

于 2013-08-27T08:09:26.943 回答
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;
于 2013-08-27T08:27:27.523 回答
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
于 2013-08-27T08:12:39.233 回答
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
于 2013-08-27T08:35:04.580 回答
0

尝试做这样的事情。

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

无需加入或子选择语句。

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

于 2013-08-27T08:37:31.583 回答