我有一张帖子和一张评级表。一个帖子可以有很多评级,评级可以是任何正整数。
在SQL中,如何表达SELECT查询,该查询将返回按其评级总和排序的帖子?
供参考,示例模式:
CREATE TABLE Posts (
id INT PRIMARY_KEY
);
CREATE TABLE Ratings (
id INT PRIMARY_KEY,
post_id INT REFERENCES Posts(id),
rating INT
);
另外,我只需要帖子,但这主要是无关紧要的。
您不清楚是否要发布没有评分的帖子。如果是这样,请使用left join
:
select p.post, sum(r.rating)
from post p left join
ratings r
on p.post = r.post
group by p.post
order by sum(r.rating) desc;
(我假设你想要最高的金额;因此desc
。)
如果您只想要评分的帖子,则不需要join
:
select r.post, sum(r.rating)
from ratings r
group by r.post
order by sum(r.rating) desc;
假设有2个表,主键和外键使用,以及可以重复使用帖子名称的事实,我提出以下内容:
select p.post_name, sum(r.rating) as post_rating
from posts p, ratings r
where p.post = r.post
group by r.post, p.post_name
order by post_rating desc, post_name asc
.headers on
create table posts ( 'posts' char(20)) ;
create table ratings ( posts char(20), 'rating' number) ;
insert into post values ( 'post1') ;
insert into post values ( 'post2') ;
insert into post values ( 'post3') ;
insert into ratings values ( 'post1', 1 ) ;
insert into ratings values ( 'post1', 3 ) ;
insert into ratings values ( 'post1', 6 ) ;
insert into ratings values ( 'post2', 2 ) ;
insert into ratings values ( 'post2', 8 ) ;
insert into ratings values ( 'post3', 1 ) ;
insert into ratings values ( 'post3', 1 ) ;
select a.post , sum(b.rating) from post a
join ratings b on a.post = b.post
group by a.post
order by sum(b.rating) ;
输出:
post|sum(b.rating)
post3|2
post1|10
post2|10