I want to update last_test_date only when there are entries in car_log without status 'test' and I really think this code is horrible, is there any way how to write it better?
UPDATE car SET last_test_date =
(SELECT date FROM car_log WHERE car_log.car_id = car.id AND
car_log.status != 'test' ORDER BY date DESC LIMIT 0,1)
WHERE (SELECT COUNT(*) FROM car_log WHERE car_log_id = client.id AND
car_log.status != 'test') > 0;
Use @@ROWCOUNT to get the last query rows count, this way you will not repeat the select
...
WHERE @@ROWCOUNT > 0;
An update join syntax will make your statement much clearer:
UPDATE car
JOIN (SELECT car_id, MAX(date) AS max_date
FROM car_log
WHERE car_log.status != 'test') ON car_log.car_id = car.id AND
SET last_test_date = max_date
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.