使用GROUP_CONCAT

时间:2015-11-13 05:08:46

标签: mysql sql

我有3个表,称为商店,服务和评级。

商店

Shops have

服务为商店提供多种服务 enter image description here

评级具有商店的评级 enter image description here

我需要通过服务获取商店详细信息,并在单个查询中评分。

我已完成此查询

select shops.*, count(distinct rating.id) as rating_count, 
sum(rating.rating) as total_rating,
GROUP_CONCAT(distinct services.servicename SEPARATOR " <=> ") as servicename
from shops
LEFT JOIN rating on rating.shop_id = shops.id
LEFT JOIN services on services.shop_id = shops.id
group by shops.id

它返回 enter image description here

但是shop1总共有21个。但它显示了42.

我需要正确的总评分以及该商店的所有服务。

选中此fiddle

1 个答案:

答案 0 :(得分:0)

select q1.id, q1.shopname, q1.rating_count, q1.total_rating,
GROUP_CONCAT(distinct services.servicename SEPARATOR " <=> ") as servicenamefrom
FROM
(select shops.*, count(distinct rating.id) as rating_count, 
sum(rating.rating) as total_rating
from shops
LEFT JOIN rating on rating.shop_id = shops.id
group by shops.id) q1
LEFT JOIN services on services.shop_id = q1.id
GROUP BY q1.id,  q1.shopname, q1.rating_count, q1.total_rating

http://sqlfiddle.com/#!9/ece82/20

要了解您的问题,请运行select w / o group by,然后检查在连接之后但在聚合之前获得的行。您将发布重复计算的来源。