我正在创建一个 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/