MYSQL:检索最新的唯一记录

时间:2009-09-06 20:16:16

标签: mysql

我有一个表记录member_id重复的行。

列字段为:

id: int(7)主键,自动增量
member_id: int(7)索引
item_qt: int(7)

+----+-----------+---------+----------+
| id | member_id | item_qt |timestamp |
+----+-----------+---------+----------+
|553 | 107       | 10      | 00:17:53 |
+----+-----------+---------+----------+
|552 | 107       | 25      | 00:17:51 | 
+----+-----------+---------+----------+
|551 | 122       | 6       | 00:17:43 |
+----+-----------+---------+----------+
|550 | 122       | 9       | 00:17:22 |
+----+-----------+---------+----------+
|549 | 107       | 19      | 00:17:11 |
+----+-----------+---------+----------+ 



首先,哪个查询会检索这些结果?

  • 选择最新的唯一行

(这篇文章给了我一些指导) Retrieve last (latest) distinct highest value

+----+-----------+---------+----------+
| id | member_id | item_qt |timestamp |
+----+-----------+---------+----------+
|553 | 107       | 10      | 00:17:53 |
+----+-----------+---------+----------+
|551 | 122       | 6       | 00:17:43 |
+----+-----------+---------+----------+



接下来,你如何得到这个?

+----+-----------+---------+----------+-------------+
| id | member_id | item_qt |timestamp | item_qt_sum |
+----+-----------+---------+----------+-------------+
|553 | 107       | 10      | 00:17:53 | 54          |
+----+-----------+---------+----------+-------------+
|551 | 122       | 6       | 00:17:43 | 15          |
+----+-----------+---------+----------+-------------+
  • 将item_qt与<中的行数相加5分钟时间

3 个答案:

答案 0 :(得分:1)

SELECT * 
FROM table t
JOIN ( SELECT MAX( id ) AS id, SUM( item_qt ) AS sum_item_qt
FROM table
WHERE `timestamp` >= DATE_SUB( NOW( ) , INTERVAL 5
MINUTE )
GROUP BY member_id
)t2 ON t2.id = t.id
ORDER BY t.id DESC
LIMIT 10

答案 1 :(得分:0)

不确定这一切是如何组合在一起的,因为我没有100%理解你在问什么......

获取表格中的最后一行

select top 1 * from [table] order by id desc

总结一个柱子

select sum(item_qt) as SumItem_qt from [table]

对于加入只是谷歌“内部联接”

排序desc只是按列名desc

排序

答案 2 :(得分:0)

好的,然后使用......

SELECT un.name, t.item_qt
FROM TABLE t
JOIN USERNAME un ON un.id = t.member_id
ORDER BY t.id DESC LIMIT 1;

你也可以用say LIMIT 5来获得5条记录......

当你说慢的时候是什么意思?可能看起来有一个我们不知道的问题。 我怀疑可能有很多记录而没有索引......

发布两个表的模式可能是明智之举,因此我们可以进一步帮助您....还要指出每个表中的行数....