我正在尝试按用户对desc的评分来检索所有图书:
我将费率保留在中间表BooksRates中,因为同一本书将有多个费率,现在我想在一个查询中同时从数据库中检索前10个评分最高的图书,并且还包含费率。
例如:
哈利·波特4.5费率
def input_output_decorator(preprocess=None, postprocess=None):
def decorator(func):
if preprocess and postprocess:
def func_wrapper(*args, **kwargs):
return postprocess(func(preprocess(*args, **kwargs)))
elif preprocess:
def func_wrapper(*args, **kwargs):
return func(preprocess(*args, **kwargs))
elif postprocess:
def func_wrapper(*args, **kwargs):
return postprocess(func(*args, **kwargs))
else:
return func
return wraps(func)(func_wrapper)
return decorator
此查询未返回所需结果。
答案 0 :(得分:0)
首先,您将得到Rate
中每本BookId
的平均group by
,然后加入Books
以获取每本书的详细信息:
SELECT b.*, g.Rate FROM Books AS b INNER JOIN (
SELECT T1.BookId, AVG(T2.Rate) AS Rate
FROM Books AS T1
INNER JOIN BookRates as T2
ON T1.BookId = T2.BookId
GROUP BY T1.BookId
) AS g on g.BookId = b.BookId
ORDER BY g.Rate desc
如果某些图书未得到评级,则必须使用左联接:
SELECT b.*, coalesce(g.Rate, 0) AS Rate FROM Books AS b LEFT JOIN (
SELECT T1.BookId, AVG(T2.Rate) AS Rate
FROM Books AS T1
INNER JOIN BookRates as T2
ON T1.BookId = T2.BookId
GROUP BY T1.BookId
) AS g on g.BookId = b.BookId
ORDER BY coalesce(g.Rate, 0) desc