我有两个表食谱和评级。我只想得到食谱,评级中的星级AVG高于4(星星)。数据库是MySQL
结构:
食谱 - ID - 标题 - 预告片 - 说明
评分 - ID - recipeid(来自食谱的id) - 明星
有人可以帮我查询吗?
答案 0 :(得分:0)
您只需将该条件放在having
子句中:
select recipes.*
from recipes
inner join ratings on recipes.id = ratings.recipeid
group by recipes.id
having avg(ratings.stars) > 4
答案 1 :(得分:0)
您需要的是加入(https://www.w3schools.com/sql/sql_join.asp),然后是(https://www.w3schools.com/sql/sql_groupby.asp)组。这些是非常基本的SQL概念,如果您要使用该语言,您需要真正学习。 w3schools教程非常好。
SELECT Recipes.title , AVG(Ratings.stars) as avgRating
FROM Recipes INNER JOIN Ratings ON Recipes.id = Ratings.recipeid
GROUP BY Recipes.title
WHERE AVG(Ratings.stars) > 4
答案 2 :(得分:0)
您需要group by
和having
的组合。这将返回所有食谱的ID和标题,平均评分超过4星:
select re.id, re.title, avg(ra.stars)
from Recipes re inner join Ratings ra on re.id = a.recipeid
group by re.id
having avg(ra.stars) > 4;
请参阅this fiddle以获取5.6中的工作演示,或this fiddle获取5.7版本和any_value
。
答案 3 :(得分:0)
以下逻辑相同。关键是要有条件结合起来。 哪个部门有更多 超过10名员工?
SELECT deptno, COUNT(*) AS "Number of employees"
FROM Employee
GROUP BY deptno HAVING COUNT(*) > 10
ORDER BY deptno