SQL - 仅在子查询不为null时更新

时间:2015-05-20 18:11:07

标签: mysql sql-update

我想只在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;

2 个答案:

答案 0 :(得分:2)

使用@@ ROWCOUNT获取最后一个查询行数,这样就不会重复选择

...
WHERE @@ROWCOUNT > 0;

答案 1 :(得分:0)

更新连接语法将使您的陈述更清晰:

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