gpt4 book ai didi

javascript - 计算并存储表列值的平均值

转载 作者:行者123 更新时间:2023-12-02 21:28:30 25 4
gpt4 key购买 nike

我有一个卡车表和一个(食品)卡车表和卡车评级。 Truck_reviews 表存储客户可以给餐车留下的评论:

enter image description here

enter image description here

如上所示,truck_reviews 表包含一个 star_ rating 列。我想获取特定卡车的所有星级并计算它们的平均值,然后将该平均值存储在卡车表的 avg_ rating 列中。我一直不知道如何做到这一点。帮忙?

如果它有助于将事情放在上下文中,一位 friend 向我发送了有关如何进行的建议:

you could create a weighted average based on the number of reviews. So you'll also need to create a column that keeps track of the total number of reviews. Every time a new rating comes in, you can do:

(current_avg * current_total_no_of_ratings) + new_rating / current_total_no_of_ratings + 1

That will give you the new avg. Whenever you do this make sure you always increment the total number of ratings in the table by 1

最佳答案

我不建议每次新卡车评论出现时都更新卡车表(例如 avg_ rating 列)。它会增加数据库的复杂性和额外的操作,这是可以避免的。

首先请重新考虑是否需要将此值保留在数据库中。您始终可以使用简单的查询来提取它,例如:

SELECT AVG(star_rating) FROM truck_reviews WHERE truck_id = x

但是,如果您确实需要在数据库中将其与所有剩余卡车数据一起查看,我建议您创建一个 View 。您可以像查询表一样查询它。要创建它,您需要类似以下内容:

CREATE VIEW trucks_view AS
SELECT *,
(select AVG(star_rating) from trucks_reviews where truck_id = trucks.id) as 'avg_rating'
FROM trucks

然后你可以向 View 询问卡车详细信息

SELECT * FROM trucks_view 

它将返回您所需要的内容

关于javascript - 计算并存储表列值的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60676946/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com