- SQL LIMIT to get latest records
- tbl_items
- ---------------------------------------------
- item_id | item_name | item_value | timestamp
- ---------------------------------------------
- tbl_categories
- -----------------------------
- cat_id | item_id | timestamp
- -----------------------------
- 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
- 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
- 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 | |
- +----------------+------------+------+-----+---------+-------+
- SELECT e.item_id, e.item_value
- FROM
- tbl_items AS e
- JOIN
- tbl_categories AS cat
- on e.item_id = cat.item_id
- WHERE
- cat.cat_id = 6001
- ORDER BY
- e.timestamp
- LIMIT 25
- create index idx_1 on tbl_categories( cat_id, item_id)
- create index idx_2 on tbl_items( item_id, timestamp)
- select T.cat_id, T.item_id, T.item_value from
- (SELECT cat.cat_id, e.item_id, e.item_value
- FROM
- tbl_items AS e
- JOIN
- tbl_categories AS cat
- on e.item_id = cat.item_id
- ORDER BY
- e.timestamp
- LIMIT 25
- ) T
- WHERE
- T.cat_id between 6001 and 6012
- ORDER BY
- T.cat_id, T.item_id