I am trying to update the status if all the rows value is set to same value.
my query like this
$ord = "SELECT * FROM plitems WHERE pur_order_id='".$order_id."'";
$ord1 = mysqli_query($con, $ord);
while($ord2 = mysqli_fetch_array($ord1)) {
if(($ord2['invoice_status']=='Invoiced'))
{
$m5 = mysqli_query($con, "UPDATE pur_orders SET status='Invoiced' WHERE pur_order_id='".$order_id."'");
}
else
{
$m5 = mysqli_query($con, "UPDATE pur_orders SET status='Partial' WHERE pur_order_id='".$order_id."'");
}
But here i have 2 line items in plitems
table, 1st line item status is Invoiced
and 2nd line item status is Partial
, But still it is setting pur_orders
status as Invoiced instead of Partial
Use a query that uses GROUP BY
to find the orders that have all the same status.
UPDATE pur_orders AS p
CROSS JOIN (
SELECT MAX(invoice_status) AS invoice_status
FROM plitems
WHERE pur_order_id = $order_id
HAVING COUNT(DISTINCT invoice_status) = 1) AS t
SET p.status = t.invoice_status
WHERE p.pur_order_id = $order_id
If there's just one status, the subquery will return one row with that status, and it will then be assigned to pur_orders.status
. If there's more than one status, the subquery will return no rows, so the CROSS JOIN
will produce an empty cross product, and it won't update anything.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.