使用子查询打开DUPLICATE KEY UPDATE查询

时间:2015-04-15 10:25:58

标签: mysql

我有一张表,我在其中插入价值,这是另一张表中价格的平均值。 我正在使用ON DUPLICATE KEY UPDATE查询,但问题是我正在从子查询更新值,并且它返回错误,该列不能为空。

insert into `averge_figures` (`full_postcode`,`property_type`,`bedrooms`,`rental_figure`)
    select p.full_postcode,p.property_type,p.bedrooms,

    ((select avg(p2.price) as price1 from property p2  where p.full_postcode=p2.full_postcode and p.bedrooms=p2.bedrooms
      and p.property_type=p2.property_type and p2.trans_type_id=2 )+
     (select avg(s.price) as price2 from sale_detail s where s.proptype=p.property_type and s.bedrooms=p.bedrooms 
     and s.postcode=p.full_postcode and s.rentorsale='R'))/2 

   from property p 
 ON DUPLICATE KEY UPDATE  `rental_figure`=

 ((select avg(p2.price) as price1 from property p2  where p.full_postcode=p2.full_postcode and p.bedrooms=p2.bedrooms
  and p.property_type=p2.property_type and p2.trans_type_id=2 )+
 (select avg(s.price) as price2 from sale_detail s where s.proptype=p.property_type and s.bedrooms=p.bedrooms 
 and s.postcode=p.full_postcode and s.rentorsale='R'))/2

任何正文都可以更正我的mysql查询。

1 个答案:

答案 0 :(得分:1)

您可以使用:

ON DUPLICATE KEY UPDATE  `rental_figure` = VALUES(`rental_figure`)
如果没有重复,

VALUES()将返回插入的值。