mysql - 带子查询的 ON DUPLICATE KEY UPDATE 查询

标签 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 查询吗?

最佳答案

您可以使用:

ON DUPLICATE KEY UPDATE  `rental_figure` = VALUES(`rental_figure`)

VALUES() 返回如果没有重复项则将插入的值。

关于mysql - 带子查询的 ON DUPLICATE KEY UPDATE 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29647768/

相关文章:

mysql - 使用数据库迁移与工作台

mysql - SQL:检测重复客户

python - 在python脚本中执行mysql命令

php - 原始查询适用于 phpmyadmin 但不适用于 laravel

php - 显示 mysql 表中两列的全名

php - 更改查询字符串/url 或替换 url/wordpress 永久链接的一部分

php - mysql LOAD DATA INFILE 生成虚拟数据

mysql - 在 Tableau 中将现有工作簿从 Oracle 重新指向 AWS-RDS?

mysql - 将日期转换为周

javascript - 从 PHP 到 JQuery 的 JSON 值并运行函数