I’m facing a mySQL problem :
I got a mySQL table wich contains these columns, it’s store every orders and every state of the orders :
id_order_history / id_employee / id_order / id_order_state / date_add
I would like to get a list of *id_order* which are in a specific *id_order_state* – let’s say 10 – but i don’t want to get the orders where the state change after this particular state and don’t want to collect the orders which are less than 7 day old …
Here is how i tought to do this :
First a query to get a list of orders & date :
SELECT id_order, date
FROM '._DB_PREFIX_.'ps_order_history,
WHERE TO_DAYS(NOW()) - TO_DAYS(date_add) <= 7
AND id_order_state = 10
then a loop to get only the orders without newest state :
$query = ' SELECT id_order, date
FROM '._DB_PREFIX_.'ps_order_history,
WHERE ';
foreach ( $listAbove, $item) {
$query =+ '
(( date > $item['date'])
AND ( id_order = $item['id']))
';
}
$orderlist = Db::getInstance()->ExecuteS($query);
It’s not really optimise, i pretty sure i can do it with only one query but don’t really know how.
Do you have a clue to how make this cleaner ?
If I’m understanding this right, you only want the orders where the most recent state is equal to 10, for example. So lets start by getting the orders and the most recent state
That gives us the latest order history item for each order (assuming
id_order_historyis the PK and that the largest value indicates the most recent order entry). Now we just search on that subquery to find the criteria we want.