[英]SQL - update only if subquery is not null
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? 我只想在car_log中有没有状态“ test”的条目时更新last_test_date,我真的认为这段代码太可怕了,有什么办法可以更好地编写它吗?
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 使用@@ ROWCOUNT获取最后一个查询行数,这样就不会重复选择
...
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.