【发布时间】:2012-02-12 01:25:15
【问题描述】:
我正在编写一个脚本,它将列出所有 12 个类别中的 25 个项目。数据库结构如下:
tbl_items
---------------------------------------------
item_id | item_name | item_value | timestamp
---------------------------------------------
tbl_categories
-----------------------------
cat_id | item_id | timestamp
-----------------------------
tbl_items 表中有大约 600,000 行。我正在使用这个 SQL 查询:
SELECT e.item_id, e.item_value
FROM tbl_items AS e
JOIN tbl_categories AS cat WHERE e.item_id = cat.item_id AND cat.cat_id = 6001
LIMIT 25
在循环中使用相同的查询 cat_id 从 6000 到 6012。但我想要每个类别的最新记录。如果我使用类似的东西:
SELECT e.item_id, e.item_value
FROM tbl_items AS e
JOIN tbl_categories AS cat WHERE e.item_id = cat.item_id AND cat.cat_id = 6001
ORDER BY e.timestamp
LIMIT 25
..查询进行大约 10 分钟的计算,这是不可接受的。我可以更好地使用LIMIT 来提供每个类别的最新 25 条记录吗?
没有ORDER BY,谁能帮我实现这个目标?任何想法或帮助将不胜感激。
编辑
tbl_items
+---------------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------------+--------------+------+-----+---------+-------+
| item_id | int(11) | NO | PRI | 0 | |
| item_name | longtext | YES | | NULL | |
| item_value | longtext | YES | | NULL | |
| timestamp | datetime | YES | | NULL | |
+---------------------+--------------+------+-----+---------+-------+
tbl_categories
+----------------+------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------------+------------+------+-----+---------+-------+
| cat_id | int(11) | NO | PRI | 0 | |
| item_id | int(11) | NO | PRI | 0 | |
| timestamp | datetime | YES | | NULL | |
+----------------+------------+------+-----+---------+-------+
【问题讨论】:
-
请显示您的表创建语句。您的索引是否正确?
-
@Astha - 请您确认您拥有哪些索引,以及是否可以请求/创建新索引?
-
从问题中不清楚整个结果是按时间戳排序还是按组内数据排序?
标签: mysql sql sql-order-by limit greatest-n-per-group