计划
- 获取按每个行业分组的赞成票数
- 获取按每个行业分组的反对票数
- 将所有 trad 左连接到具有评分函数、排序依据和限制为 4 的上述数据源
示例输入
create table question
(
id_question integer primary key not null
-- other metadata here..
);
create table trad
(
id_trad integer primary key not null,
id_question integer not null,
foreign key ( id_question ) references question ( id_question )
);
create table vote_up
(
id_vote_up integer primary key not null,
id_trad integer not null,
foreign key ( id_trad ) references trad ( id_trad )
);
create table vote_down
(
id_vote_down integer primary key not null,
id_trad integer not null,
foreign key ( id_trad ) references trad ( id_trad )
);
insert into question
( id_question )
values
( 1 )
;
insert into trad
( id_trad, id_question )
values
( 1, 1 ),
( 2, 1 ),
( 3, 1 ),
( 4, 1 ),
( 5, 1 ),
( 6, 1 ),
( 7, 1 )
;
insert into vote_up
( id_vote_up, id_trad )
values
( 1, 1 ),
( 2, 1 ),
( 3, 1 ),
( 4, 1 ),
( 5, 1 ),
( 6, 1 ),
( 7, 3 ),
( 8, 3 ),
( 9, 3 ),
( 10, 3 ),
( 11, 4 ),
( 12, 4 ),
( 13, 5 ),
( 14, 6 ),
( 15, 6 ),
( 16, 7 ),
( 17, 7 ),
( 18, 7 )
;
insert into vote_down
( id_vote_down, id_trad )
values
( 1, 1 ),
( 2, 1 ),
( 3, 1 ),
( 4, 1 ),
( 5, 1 ),
( 6, 1 ),
( 7, 3 ),
( 8, 3 ),
( 9, 3 ),
( 10, 4 ),
( 11, 4 )
;
查询
select trad.id_trad, coalesce(upvotes, 0) - coalesce(downvotes, 0) as score
from trad
left join
(
select
trad.id_trad, count(*) as upvotes
from trad
inner join vote_up
on trad.id_trad = vote_up.id_trad
group by 1
) uv
on trad.id_trad = uv.id_trad
left join
(
select
trad.id_trad, count(*) as downvotes
from trad
inner join vote_down
on trad.id_trad = vote_down.id_trad
group by 1
) dv
on uv.id_trad = dv.id_trad
where trad.id_question = 1
order by score desc
limit 4
;
输出
+---------+-------+
| id_trad | score |
+---------+-------+
| 7 | 3 |
| 6 | 2 |
| 3 | 1 |
| 5 | 1 |
+---------+-------+
sqlfiddle ( separate structures )
注意
还可以考虑将您的投票重组为一张表格。 atm vote_up 和
vote_down 不必要地重复相同的结构..
这看起来像:
sqlfiddle ( reuse structure )