Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL UPDATE with subquery for null

Tags:

mysql

I'm trying to update the status of all airplanes, using a subquery, to 'OUT' who are currently out and have not returned. My foreign key is PLANE_NUM. I'm trying it like this but I've got an error:

UPDATE plane
SET STATUS='OUT'
WHERE PLANE_NUM 
IN (SELECT *
    FROM plane p, flight f
    WHERE p.PLANE_NUM = f.PLANE_NUM
    AND FLIGHT_RETURNDATE IS null);
like image 253
alcor8 Avatar asked Sep 05 '26 01:09

alcor8


2 Answers

A better way of doing is by joining as

update plane p
left join flight f
on p.PLANE_NUM = f.PLANE_NUM
SET p.STATUS='OUT'
where f.FLIGHT_RETURNDATE IS null ;
like image 190
Abhik Chakraborty Avatar answered Sep 07 '26 15:09

Abhik Chakraborty


problem you are facing is because ==> MySQL doesn’t allow referring to a table that’s targeted for update in a FROM clause, which can be frustrating.

This will work for you

UPDATE plane
SET STATUS='OUT'
WHERE PLANE_NUM 
IN (SELECT * FROM (select p.PLANE_NUM
    FROM plane p, flight f
    WHERE p.PLANE_NUM = f.PLANE_NUM
    AND FLIGHT_RETURNDATE IS null) as B );

Not Optimized. Please refer to links below and optimize as per your requirement

You can't specify target table for update in FROM clause

http://www.xaprb.com/blog/2006/06/23/how-to-select-from-an-update-target-in-mysql/

like image 39
Raj Avatar answered Sep 07 '26 16:09

Raj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!