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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法