Reputation: 2656
How can I select the latest records (=MAX(order_history_id) from this table (one [latest] row per order_id):
+----------------+--------+-------+----------+
|order_history_id|order_id|trackc |date_added|
+----------------+--------+-------+----------+
| 4400 | 1000 | text | 2014-9-24|
| 4401 | 1001 | text2 | 2014-9-26|
| 4410 | 1000 | text3 | 2014-9-29|
| 4411 | 1003 | text4 | 2014-9-20|
+----------------+--------+-------+----------+
My current query is:
SELECT * FROM order_history WHERE trackc <> '' GROUP BY order_id
Upvotes: 4
Views: 104
Reputation: 1819
select t1.* from order_history t1
inner join(
select order_id,max(order_history_id) as order_history_id
from order_history
where ifnull(trackcode,'') <> ''
group by order_id
) as t2 on t1.order_history_id = t2.order_history_id
Upvotes: 3
Reputation: 27042
SELECT * from order_history as oh inner join (
SELECT MAX(order_history_id) AS max_id, order_id
FROM order_history
GROUP BY order_id
) as t ON t.max_id = oh.order_history_id
WHERE oh.trackc <> ''
The sub-query extract the max value for every order_id. Than joins the found values with order_history and extracts every fields.
Upvotes: 1
Reputation: 39
select or.order_history_id,or.order_id,or.trackc,or.date_added From order_history or
order by or.order_id Desc
limit 1;
Upvotes: -1