[英]direction on (My)SQL left/right/inner join
While getting a list of restaurant I want to join rating data in this list. 在获取餐厅列表时,我想在此列表中加入评分数据。
For example 例如
Table1 – restaurant Columns: id, name, latitude, longitude
and 和
Table2 – ratings Columns: id, restaurant_id, rating (value options: 1, 2, 3, 4, 5)
Constructed this: 构造此:
SELECT *, SUM(ratings.rating) AS total_rating_count
FROM restaurants
INNER JOIN ratings
ON ratings.restaurant_id = restaurants.id
This only returns me 1 restaurant. 这只会给我返回1家餐厅。 I also need the amount of ratings available per restaurant in able to calculate average rating.
我还需要每个餐厅可用的评分数量,以便能够计算平均评分。
Can use some direction on this. 可以对此使用一些指导。
EDIT : And while we are at it, I want to join another table with comments linked to restaurant. 编辑 :而当我们在它的时候,我想加入另一个表与链接到餐厅的评论。 I should dive into this at the same time: What is the difference between Left, Right, Outer and Inner Joins?
我应该同时深入探讨以下内容: 左,右,外部和内部连接之间有什么区别?
You need GROUP BY
clause: 您需要
GROUP BY
子句:
SELECT
*, AVG(ratings.rating) AS avg_rating_count
FROM
restaurants
INNER JOIN ratings ON ratings.restaurant_id = restaurants.id
GROUP BY
restaurants.id
-since you've mentioned average value, I've placed AVG() function in query. -因为您已经提到平均值,所以我在查询中放置了AVG()函数。 But be aware that this is invalid in normal SQL (mixing of non-group columns with group functions) - and in terms of MySQL DBMS doesn't specify which row will be returned.
但是请注意,这在常规SQL(将非组列与组函数混合)中是无效的-就MySQL DBMS而言,它没有指定将返回哪一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.