doudi8519 2012-07-09 23:37 采纳率: 100%
浏览 43
已采纳

如何使用select查询的结果更新一行的多个mysql列?

I have a reviews table that contains three ways to rate an item. The items themselves then have three columns to hold the average for each value respectively.

I could do this using three nested queries in an update query, but I feel like this is inefficient... Is there a way to update them all at once?

So far I've used this as my select query:

SELECT AVG(rating_1),AVG(rating_2),AVG(rating_3) FROM items_reviews WHERE item_id = 1

I just don't know how to use the result of that query to update an item row.

  • 写回答

1条回答 默认 最新

  • duankao4489 2012-07-10 00:00
    关注

    You could use an join in the UPDATE:

    UPDATE items a
    INNER JOIN
    (
        SELECT 
            item_id,
            AVG(rating_1) AS avg1, 
            AVG(rating_2) AS avg2, 
            AVG(rating_3) AS avg3
        FROM items_reviews
        WHERE item_id = 1
        GROUP BY item_id
    ) b ON a.item_id = b.item_id
    SET 
        a.avgrating1 = b.avg1,
        a.avgrating2 = b.avg2,
        a.avgrating3 = b.avg3
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 questasim仿真报错
  • ¥15 寻找电脑攻防的导师,有问题请教一下。
  • ¥20 微信同是win11,我的电脑安装不了pageoffice,一直无法打开
  • ¥15 这个界面我通过postman请求不到,但是通过浏览器可以正常访问
  • ¥15 动态规划算法实现背包问题
  • ¥15 wpf程序使用过程中异常奔溃
  • ¥15 多目标优化算法在与其他算法数据对比结果判断
  • ¥15 CPTN和EAST,主干网络是VGG16,请问在ICDAR2015数据集上训练之后,CPTN和EAST模型的大小为多少
  • ¥15 按颜色进行点云分割-python
  • ¥15 Matlab如何实现汽车变道切入场景的批量仿真