mysql - 如何创建从另一个表的列自动计算平均值的列

标签 mysql

我正在创建一个 Web 应用程序,我将在其中显示包含公司名称和用户评分的表格。如果有一个包含所有公司平均评级的列,当有新条目时自动更新,这对我来说会容易得多。 例如,假设我有公司表:

╔════╤═════════════════════╤═══════════════╗
║ id │ nameOfTheCompany    │ owner         ║
╠════╪═════════════════════╪═══════════════╣
║ 1  │ Computer Repair LLC │ John Doe      ║
╟────┼─────────────────────┼───────────────╢
║ 2  │ Unimatrix           │ Barrack Obama ║
╚════╧═════════════════════╧═══════════════╝

还有服务表,其中每项服务都由用户证明和评分(idCompany 是 FK)。

╔════╤═══════════╤═══════════════════════════════════════════════╤═══════════╗
║ id │ idCompany │ serviceType                                   │ userGrade ║
╠════╪═══════════╪═══════════════════════════════════════════════╪═══════════╣
║ 1  │ 1         │ Installing antivirus and antispyware software │ 3         ║
╟────┼───────────┼───────────────────────────────────────────────┼───────────╢
║ 2  │ 2         │ Replacing new HDD                             │ 4         ║
╟────┼───────────┼───────────────────────────────────────────────┼───────────╢
║ 3  │ 1         │ Replacing new RAM                             │ 1         ║
╟────┼───────────┼───────────────────────────────────────────────┼───────────╢
║ 4  │ 2         │ CPU Cleaning                                  │ 5         ║
╚════╧═══════════╧═══════════════════════════════════════════════╧═══════════╝

我想在第一个表中创建新列:

╔════╤═════════════════════╤═══════════════╤═══════════════╗
║ id │ nameOfTheCompany    │ owner         │ averageRating ║
╠════╪═════════════════════╪═══════════════╪═══════════════╣
║ 1  │ Computer Repair LLC │ John Doe      │ 2             ║
╟────┼─────────────────────┼───────────────┼───────────────╢
║ 2  │ Unimatrix           │ Barrack Obama │ 4.5           ║
╚════╧═════════════════════╧═══════════════╧═══════════════╝

最佳答案

此查询将为您提供结果。

    select  c.*, avg(userGrade) as averageRating from table.company c join table.service s on c.id=s.idCompan group by s.idCompany;

您还可以使用此查询创建 View 。

希望对你有帮助

关于mysql - 如何创建从另一个表的列自动计算平均值的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38336869/

相关文章:

MYSQL 如果没有结果我需要一些默认值

mysql - 尝试按多列排序,只需要具有多个值的列的值

php不执行mysql的查询,但在mysql中是可执行的

PHP filemtime vs MySQL 最后更新时间戳用于 CMS 中的图像缓存

asp.net - 所有数据都不适合数据 GridView

php - 如何在mysql中插入额外的文本?

java - mysql 之间和通过 JDBC preparedstatement 使用 - 获取参数索引超出范围异常

mysql - 能够在 ServiceStack/ORMLite codefirst 中创建聚簇索引

php - 将选项从下拉列表插入数据库

mysql - 大查询 SQL 中其他列中 2 个提取列的总和