MySQL:使用嵌套子查询进行更新

时间:2017-09-27 15:05:15

标签: mysql sql nested subquery

我正在努力使这个查询工作。目的是在最短日期列表之间获得最短日期。

但是我得到了:'where子句'中的未知列'di.device_id'

如何在第二个子查询中公开device_id字段?

update device_information di
set first_seen=(
  select min(date) from (
    select min(insert_date) date from product_state_change_event where device_id=di.device_id
    union select min(insert_date) date from sensor_range_switch_change_event where device_id=di.device_id
  ) as dates
);

被修改

事实上,我有19个表来联合

2 个答案:

答案 0 :(得分:0)

我希望这样的查询:

update device_information di join
       (select min(insert_date) as minid
        from product_state_change_event psce
        group by psce.device_id 
       ) psce
       on psce.device_id = di.device_id
    set first_seen = least(psce.insert_date, psce.minid);

这假设日期永远不会是NULL。这很容易纳入答案(通过向least()添加更多逻辑)。

答案 1 :(得分:0)

如果有人想知道我是如何解决的:

update device_information di
join (
  select identifier, min(date) date from (
    select client_var_name identifier, min(insert_date) date from product_state_change_event group by client_var_name
    union all select client_var_name identifier, min(insert_date) date from sensor_range_switch_change_event group by client_var_name
    ...
  ) as unique_dates group by identifier
) as dates on di.identifier = dates.identifier
set di.first_seen = dates.date;