如何为用户获取最后插入的值?

时间:2014-04-01 12:58:53

标签: mysql sql

我有这个MYSQL表...

+----+---------+-----------+---------------+------------+---------------------+
| id | user    | val1      | val2          | val3       | last_modified_date  |
+----+---------+-----------+---------------+------------+---------------------+
|  1 |    0001 |         1 |             1 |          1 | 2014-03-31 16:53:29 |
|  2 |    0100 |         1 |             1 |          1 | 2014-04-01 10:32:50 |
|  3 |    0200 |         1 |             0 |          0 | 2014-04-01 10:34:13 |
|  4 |    0200 |         1 |             1 |          1 | 2014-04-01 14:43:47 |
+----+---------+-----------+---------------+------------+---------------------+

我想要实现的是获取为用户创建的所有最后一个(按时间顺序)值集。

在给出的示例中,我们为用户0200插入0,但在4小时后插入1.我希望能够插入最后一个值(1)。

我有这个问题:

select * 
from table 
where val3 = 1 
group by user 
order by last_modified_date desc;

更通用的

select * from table group by user order by last_modified_date desc;

这些查询似乎对示例表工作正常。它们对每个案例都是正确的吗?如何判断“选择所有将val3 = 1作为最后插入值的用户”?

2 个答案:

答案 0 :(得分:1)

试试这个

select * from table as t1
where val3 = 1 
and last_modified_date =
(select max(last_modified_date) as  last_modified_date from table as t2
where t1.user=t2.user and t2.val3 = 1 );

答案 1 :(得分:1)

您可以使用以下两种方法之一:

选项1 - 获取每个用户的最后一条记录并过滤t.val3

SELECT t.*
FROM table t
JOIN (
    SELECT MAX(last_modified_date) as last_modified, user
    FROM table
    GROUP BY user
) as tt ON t.user = tt.user AND t.last_modified_date = tt.last_modified_date
GROUP BY user
HAVING val3 = 1

选项2 - 获取t.val3 = 1的所有记录并删除不属于最后的记录:

SELECT t.*
FROM table t
LEFT JOIN table tt ON tt.user = t.user AND tt.last_modified_date > t.last_modified_date
WHERE t.val3 = 1
AND tt.id IS NULL