在不使用限制的情况下为用户选择最新记录

时间:2013-11-24 06:35:24

标签: mysql sql

在这种情况下,是否有一种安全的方法来获取id和用户的最新记录而不使用我在下面做的限制?

表格

"id"    "head"  "type"  "updated"   "userId"    "addedDate"
"1"     "2"     "0"     "1"         "1"         "2013-11-24 11:33:04"
"1"     "2"     "1"     "1"         "1"         "2013-11-24 11:56:35"
"2"     "2"     "0"     "1"         "1"         "2013-11-24 11:55:40"
"2"     "2"     "1"     "0"         "1"         "2013-11-24 11:56:28"

当前的sql

select id, addedDate from test 
where id = 1 and userId = 1 order by addedDate desc limit 1;

尝试实现(对于上述sql而不使用限制)

"id"    "head"  "type"  "updated"   "userId"    "addedDate"
"1"     "2"     "1"     "1"         "1"         "2013-11-24 11:56:35"

4 个答案:

答案 0 :(得分:2)

这样的东西可行,但可能有更有效的方法:

SELECT id, head, type, updated, userId, addedDate 
FROM test 
WHERE id = 1 
AND userId = 1
AND addedDate = (SELECT max(addedDate) FROM test WHERE id = 1 AND userId = 1)

我不确定DATE类型的范围查询在MySQL中的效率如何。您可以进行架构更改以提供相同的输出,但在您看到某种形式的瓶颈之前我不会担心它(直到您达到数百万行时才会这样做。)

值得注意的是 - 我的解决方案没有任何保证您只能获得一行作为输出。如果用户在同一时间添加了两个条目,则输出中将收到两行。通常,如果您无法将查询限制为UNIQUE列而无法使用LIMIT 1,则必须依赖应用程序逻辑(“我们每天仅插入一次”)限制结果。

答案 1 :(得分:2)

另一种方法

SELECT t.id, t.head, t.type, t.updated, t.userId, t.addedDate
  FROM
(
  SELECT userid, id, MAX(addeddate) addeddate
    FROM test
   WHERE userid = 1
     AND id = 1
) q JOIN test t
    ON q.userid = t.userid
   AND q.id = t.id
   AND q.addeddate = t.addeddate

SELECT id, head, type, updated, userId, addedDate
  FROM
(
  SELECT id, head, type, updated, userId, addedDate,
         @n := @n + 1 rnum
    FROM test t, (SELECT @n := 0) i
   WHERE userid = 1
     AND id = 1
   ORDER BY addedDate DESC
) q 
 WHERE rnum = 1

输出:

| ID | HEAD | TYPE | UPDATED | USERID |                       ADDEDDATE |
|----|------|------|---------|--------|---------------------------------|
|  1 |    2 |    1 |       1 |      1 | November, 24 2013 11:56:35+0000 |

以下是两个查询的 SQLFiddle 演示

答案 2 :(得分:1)

使用mysql非常简单:

select *
from (
  select * from test
  order by addedDate desc) x
group by userId

这为您提供了每个用户的最新行。只获得一个用户:

select *
from (
  select * from test
  where userId = 1
  order by addedDate desc) x
group by userId

答案 3 :(得分:-1)

从test中选择id,max(addedDate),其中id = 1,userId = 1