我有两张桌子,一张是评级&第二个是property_listing
,我正在考虑SUM& AVG基于这个字段safety, entertainment, parking, public_transportation, community_centers
,我创建了这个SQL查询:
SELECT property_listing.*, coalesce( avg( rating.safety + rating.entertainment + rating.parking + rating.public_transportation + rating.community_centers )/5 , 0 ) AS rate
FROM property_listing
JOIN rating ON property_listing.property_id = rating.property_id
ORDER BY property_listing.property_id DESC
但是在运行这个SQL之后我只得到一行。为什么我没有用AVG获取其他记录?
我的SQL小提琴:http://sqlfiddle.com/#!2/b2ab0/2
[Table 1: rating]
review_id property_id user_id safety entertainment parking public_transportation community_centers
--------- ----------- ------- ------ ------------- ------- --------------------- -----------------
8 553 24 2 4 5 5 5
9 552 24 3 4 5 5 5
10 550 24 3 4 5 5 5
11 523 24 2 4 5 5 5
[Table 2: property_listing]
property_id title user_id property_type_id
----------- ------------------------------- ------- ----------------
523 Bograshov St Tel Aviv Israel IL 48 16
550 Bograshov St Tel Aviv Israel IL 54 13
552 Bograshov St Tel Aviv Israel IL 54 16
553 Bograshov St Tel Aviv Israel IL 48 16
[Wanting this result with AVG]
property_id title user_id property_type_id rating
----------- ------------------------------- ------- ---------------- ------
523 Bograshov St Tel Aviv Israel IL 48 16 4.2
550 Bograshov St Tel Aviv Israel IL 54 13 4.4
552 Bograshov St Tel Aviv Israel IL 54 16 4.4
553 Bograshov St Tel Aviv Israel IL 48 16 4.2
答案 0 :(得分:2)
尝试使用group by
子句,因为avg()
是一个聚合函数,您需要按列对结果进行分组:
SELECT property_listing.*,
COALESCE(Avg(rating.safety + rating.entertainment
+ rating.parking
+ rating.public_transportation
+ rating.community_centers) / 5, 0) AS rate
FROM property_listing
JOIN rating
ON property_listing.property_id = rating.property_id
GROUP BY property_listing.property_id
ORDER BY property_listing.property_id DESC
答案 1 :(得分:0)
以下内容应该有效:
SELECT property_listing.property_ID
, property_listing.title
, property_listing.user_ID
, property_listing.Property_Type_ID
, avg( rating.safety + rating.entertainment + rating.parking + rating.public_transportation + rating.community_centers )/5 AS rate
FROM property_listing
JOIN rating ON property_listing.property_id = rating.property_id
group by property_listing.property_ID
, property_listing.title
, property_listing.user_ID
, property_listing.Property_Type_ID
ORDER BY property_listing.property_id DESC
我不确定为什么你的查询确实没有用,但是在mysql中你不必指定组,我不能说它如何评估这样的查询。指定您的小组总是更好,这样您才能知道实际发生了什么。
我删除了合并,但如果您愿意,可以重新添加。