在与vendors表和vendor ratings表进行左连接时,只显示一条记录

oknwwptz  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(417)

这个问题在这里已经有了答案

sql对所有行进行计数,而不是对单个行进行计数(1个答案)
两年前关门了。
我有一个供应商表和供应商评级表。我试图创建一个视图,在左侧显示所有供应商,在右侧显示他们的总体评级。我希望供应商出现,即使他们还没有评级。我正在使用MySQL5.7。我的问题是:

SELECT
vendors.ID,
vendors.Vendor,
ROUND(((AVG(`Cost_Rating`) + AVG(`Documentation_Rating`) + AVG(`Safety_Rating`) + AVG(`Equipment_Rating`) + AVG(`Performance_Rating`) + AVG(`Promptness_Rating`) + AVG(`Communication_Rating`))/7.0),2) as `Overall Rating`,
vendors.`Phone #`,
vendors.`Fax #`,
vendors.Website,
vendors.`Physical Address`,
vendors.`P.O. Box`,
vendors.City,
vendors.`State`,
vendors.Zip,
vendors.`Region Serving`,
vendors.Note,
vendors.OnVendorList,
vendors.`Search Words`,
ROUND(AVG(`Communication_Rating`),2) AS `Average Communication Rating`,
ROUND(AVG(`Promptness_Rating`),2) AS `Average Promptness Rating`,
ROUND(AVG(`Performance_Rating`),2) AS `Average Performance Rating`,
ROUND(AVG(`Equipment_Rating`),2) AS `Average Equipment Rating`,
ROUND(AVG(`Safety_Rating`),2) AS `Average Safety Rating`,
ROUND(AVG(`Documentation_Rating`),2) AS `Average Documentation Rating`,
ROUND(AVG(`Cost_Rating`),2) AS `Average Cost Rating`
FROM vendors
LEFT JOIN `Vendor Ratings` ON vendors.vendor = `vendor ratings`.vendor

无论我使用什么类型的连接,我都会得到相同的结果。我的问题在哪里?

5rgfhyps

5rgfhyps1#

你失踪了 GROUP BY 在供应商身上。如果没有GROUPBY子句,查询只是计算总体聚合值(一次合并所有供应商)。
请尝试以下操作:

SELECT
vendors.ID,
vendors.Vendor,
ROUND(((AVG(`Cost_Rating`) + AVG(`Documentation_Rating`) + AVG(`Safety_Rating`) + AVG(`Equipment_Rating`) + AVG(`Performance_Rating`) + AVG(`Promptness_Rating`) + AVG(`Communication_Rating`))/7.0),2) as `Overall Rating`,
vendors.`Phone #`,
vendors.`Fax #`,
vendors.Website,
vendors.`Physical Address`,
vendors.`P.O. Box`,
vendors.City,
vendors.`State`,
vendors.Zip,
vendors.`Region Serving`,
vendors.Note,
vendors.OnVendorList,
vendors.`Search Words`,
ROUND(AVG(`Communication_Rating`),2) AS `Average Communication Rating`,
ROUND(AVG(`Promptness_Rating`),2) AS `Average Promptness Rating`,
ROUND(AVG(`Performance_Rating`),2) AS `Average Performance Rating`,
ROUND(AVG(`Equipment_Rating`),2) AS `Average Equipment Rating`,
ROUND(AVG(`Safety_Rating`),2) AS `Average Safety Rating`,
ROUND(AVG(`Documentation_Rating`),2) AS `Average Documentation Rating`,
ROUND(AVG(`Cost_Rating`),2) AS `Average Cost Rating`
FROM vendors
LEFT JOIN `Vendor Ratings` ON vendors.vendor = `vendor ratings`.vendor
GROUP BY 
  vendors.ID,
  vendors.Vendor,
  vendors.`Phone #`,
  vendors.`Fax #`,
  vendors.Website,
  vendors.`Physical Address`,
  vendors.`P.O. Box`,
  vendors.City,
  vendors.`State`,
  vendors.Zip,
  vendors.`Region Serving`,
  vendors.Note,
  vendors.OnVendorList,
  vendors.`Search Words`

另外,请注意select子句中的所有列,这些列不使用聚合函数,如 Avg() ,已添加到 Group By 条款。
do read:选择列表不在group by子句中,并且包含未聚合的列。。。。与sql不兼容\u mode=only \u full \u group by

相关问题