首页 > 解决方案 > 如何通过相关表上的列的总和对 SELECT 查询进行排序?

问题描述

我有一个帖子表和一个评级表。一篇文章可以有多个评分,评分可以是任何正整数。

在 SQL 中,我如何表达一个 SELECT 查询,该查询将返回按评分总和排序的帖子?

作为参考,示例架构:

CREATE TABLE Posts (
    id INT PRIMARY_KEY
);

CREATE TABLE Ratings (
    id INT PRIMARY_KEY,
    post_id INT REFERENCES Posts(id),
    rating INT 
);

另外,我只需要帖子,但这主要是无关紧要的。

标签: sqlsqlite

解决方案


    .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

推荐阅读