如何为特定用户选择最后一行?

时间:2016-06-23 13:38:49

标签: mysql sql

我有一张这样的表:

// requests
+----+----------+-------------+
| id | id_user  |  unix_time  |
+----+----------+-------------+
| 1  | 2353     | 1339412843  |
| 2  | 2353     | 1339412864  |
| 3  | 5462     | 1339412894  |
| 4  | 3422     | 1339412899  |
| 5  | 3422     | 1339412906  |
| 6  | 2353     | 1339412906  |
| 7  | 7785     | 1339412951  |
| 8  | 2353     | 1339413640  |
| 9  | 5462     | 1339413621  |
| 10 | 5462     | 1339414490  |
| 11 | 2353     | 1339414923  |
| 12 | 2353     | 1339419901  |
| 13 | 8007     | 1339424860  |
| 14 | 7785     | 1339424822  |
| 15 | 2353     | 1339424902  |
| 16 | 2353     | 1466272801  |
| 17 | 2353     | 1466272805  |
+----+----------+-------------+

我试图获取与特定用户相关的最后一行。例如,对于此用户id_user = 7785,我想选择此行:

| 14 | 7785     | 1339424822  |

这是我的疑问:

SELECT unix_time AS last_seen
FROM requests WHERE id = '7785'
ORDER BY unix_time DESC
LIMIT 1

但是我的查询并没有选择任何行。怎么了?

SQL fiddle

另外请注意,如果我在id_useruinx_time上创建单个索引,或者我应该在这两列(id_user, unix_time)上创建多列索引,请告诉我吗?

5 个答案:

答案 0 :(得分:6)

您使用了错误的列(id而不是id_user - 反之亦然):

SELECT unix_time AS last_seen
FROM requests WHERE id_user = '7785'
ORDER BY unix_time DESC
LIMIT 1

答案 1 :(得分:1)

让子查询返回每个id_user及其最高的unix_time。加入那个结果。

select t1.*
from tablename t1
  join (select id_user, max(unix_time) as unix_time
        from tablename
        group by id_user) t2
     on t1.id_user = t2.id_user and t1.unix_time = t2.unix_time

将返回所有用户及其最新登录信息。

如果需要有关单个用户的信息,请添加WHERE id_user = '7785'

答案 2 :(得分:1)

在WHERE条件中,您将id与id_user的id进行比较。 你的错误在第二行,应该是:

SELECT unix_time AS last_seen
FROM requests WHERE id_user = '7785'
ORDER BY unix_time DESC
LIMIT 1

答案 3 :(得分:1)

你有: WHERE id ='7785'

如果你想要行:| 7 | 7785 | 1339412951 |

您需要以下内容:

SELECT TOP 1 unix_time AS last_seen
FROM requests WHERE id_user = '7785'
ORDER BY unix_time DESC

这将获取查询的最高结果,其中user_ID等于'7785'。 'ORDER BY unix_time DESC'将具有最高单位时间的值置于顶部,以便用户最后一次请求。

答案 4 :(得分:0)

您可以使用以下查询来帮助您

 SELECT SUBSTRING_INDEX(id,',',1) AS id ,SUBSTRING_INDEX(id_user,',',1) AS id_user, unix_time FROM 
 (SELECT GROUP_CONCAT(id ORDER BY unix_time DESC )  AS id, GROUP_CONCAT(id_user ORDER BY unix_time DESC  ) AS id_user ,MAX(unix_time)  AS unix_time FROM test_71 GROUP BY id_user
  HAVING id_user='7785' ) t   ;