I have the following 2 tables order
and tracking
. The structures are the following:
Order
( columns and data ):
id fecha nroorder description
1 2017-22-01 1000001 Order1
2 2017-22-01 1000002 Order2
3 2017-22-01 1000003 Order3
Tracking
( columns and data ):
id idorder idstatus
1 1 1
2 1 2
3 1 3
4 2 1
5 2 2
6 3 1
7 3 2
The point to all this is that I need it to return each order
with the tracking
highest idstatus
, that is, I need it to return:
order.id order.fecha order.nroorder order.description tracking.idstatus
1 2017-22-01 1000001 Order1 3
2 2017-22-01 1000002 Order2 2
3 2017-22-01 1000003 Order3 2
I tried the following statement (actually several but this is the closest one):
SELECT `order`.*, d.*
FROM `order` left JOIN (SELECT tracking.*
FROM tracking
ORDER BY tracking.id DESC limit 1) d
ON `order`.`id` = d.idorder
I tracking
order it by id
, to remove the last one, because by business rule tracking
they increase their idstatus
as they are inserted.
What is wrong or what am I missing?
Try changing the query like so. The way you have it, the subquery is only going to bring you one record of all that there is and what you need is one record for each order.
A subquery could solve your question:
Your problem is that you are doing the
LIMIT
in theJOIN
; with that you only get one row oftracking
instead of one for each row oforder
.This query does what you need: