Mysql更新使用选择的值

时间:2019-05-03 09:22:11

标签: mysql

我有一个气象应用程序,我每小时将气象数据存储在数据库中。

最近我发现了一个小错误,该错误导致写了几百个错误的记录。

为解决此问题,我决定使用给定日期的平均值更新所有错误记录。

我有以下3个查询来检索所需的值:

select TRUNCATE( ( sum(temperature) / count(*) ), 2) as myTempAvg  from MY_TABLE where rawData not in ('chron', 'fallback') and DATE(transmissionDate) = DATE('2019-01-27');
select TRUNCATE( ( sum(humidity) / count(*) ), 2) as myHumyAvg  from MY_TABLE where rawData not in ('chron', 'fallback') and DATE(transmissionDate) = DATE('2019-01-27');
select TRUNCATE( ( sum(pressure) / count(*) ), 0) as myPressAvg  from MY_TABLE where rawData not in ('chron', 'fallback') and DATE(transmissionDate) = DATE('2019-01-27');

我试图找出一种在UPDATE语句中使用以上查询的方法。像这样:

update MY_TABLE set temperature = $QUERY_1_RESULT , humidity = $QUERY_2_RESULT , pressure = $QUERY_3_RESULT where rawData in ('chron', 'fallback')  and DATE(transmissionDate) = DATE('2019-01-27');

注意:$ QUERY变量说明目的占位符。

有什么主意吗?

2 个答案:

答案 0 :(得分:1)

您可以在下面尝试-

if ($query->num_rows == 1) {
}

答案 1 :(得分:1)

您应该能够像下面那样进行操作。

update MY_TABLE 
(
select TRUNCATE( ( sum(temperature) / count(*) ), 2) as myTempAvg ,
TRUNCATE( ( sum(humidity) / count(*) ), 2) as myHumyAvg,
TRUNCATE( ( sum(pressure) / count(*) ), 0) as myPressAvg
from MY_TABLE 
where rawData not in ('chron', 'fallback') and DATE(transmissionDate) = DATE('2019-01-27')
)as src
set temperature=myTempAvg ,humidity = myHumyAvg , pressure = myPressAvg
where rawData in ('chron', 'fallback')  and DATE(transmissionDate) = DATE('2019-01-27')