我在写一个脚本,它将列出所有12个类别中的25个项目。数据库结构如下:SQL LIMIT获取最新记录
tbl_items
---------------------------------------------
item_id | item_name | item_value | timestamp
---------------------------------------------
tbl_categories
-----------------------------
cat_id | item_id | timestamp
-----------------------------
表中有大约600,000行tbl_items
。我使用这个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
到6012上的环从6000相同的查询,但我想每个类别的最新记录。如果我使用类似的东西:
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 | |
+----------------+------------+------+-----+---------+-------+
请显示您的表创建语句。你的索引是否正确? – 2012-01-17 07:59:55
我编辑了这个问题。 – Astha 2012-01-17 08:10:19
@Astha - 请你确认你有什么索引,以及你是否可以请求/创建新索引? – MatBailie 2012-01-17 09:45:18