我正在编写一个脚本,它将列出所有 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
在循环中对从 6000 到 6012 的 cat_id
使用相同的查询。但我想要每个类别的最新记录。如果我使用类似的东西:
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 分钟的计算,这是 Not Acceptable 。我可以更好地使用 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 | |
+----------------+------------+------+-----+---------+-------+
最佳答案
你能添加索引吗?如果您在 timestamp
和其他适当的列上添加索引,ORDER BY
将不会花费 10 分钟。
关于mysql - SQL LIMIT 获取最新记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8891276/