1

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;

2 Answers 2

2

Use @@ROWCOUNT to get the last query rows count, this way you will not repeat the select

...
WHERE @@ROWCOUNT > 0;
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.