我有两张桌子:
[Table container]
id int
<some more fields>
latest_measurement int
[Table measurement]
id int
container_id int
unixtime bigint
现在我想latest_measurement
根据测量表中的最新测量值更新传感器表列。我已经准备好子查询来返回最新的测量值sensor_id
,这很有效:
SELECT m.fill_level
from measurement m
inner join (
select m.container_id, MAX(m.unixtime) as maxdate from measurement m GROUP BY container_id
) m2
on m2.container_id = m.container_id
where m.unixtime = m2.maxdate
但是,如果我在更新语句中使用此查询,如下所示,它将失败并出现异常:
UPDATE container
SET latest_fill_level = (
SELECT m.fill_level
from measurement m
inner join (
select m.container_id, MAX(m.unixtime) as maxdate from measurement m GROUP BY container_id
) m2
on m2.container_id = m.container_id
where m.unixtime = m2.maxdate
and container.id = m.container_id)
最后,这是一个例外:
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
如何编写一个更新语句,该语句可以从产生多个值的 SELECT 语句中使用它们各自的值更新多行?