我正在尝试制作代码问题网站,例如CodeChef。MySQL“For Each”
到目前为止,我有两个表,problems
和submissions
。
problems
由单个id
字段组成auto_increment
ed。 (它确实有更多的领域,但它们是不相关的。)
submissions
由一个id
场是auto_increment
版,一个problem_id
场是foreign key
-ed到problems.id
和bool
correct
领域。
这是他们(简体)创建语句:
create table problems
(
id bigint auto_increment primary key not null,
/* more fields that are unimportant */
);
create table submissions
(
id bigint auto_increment primary key not null,
problem_id bigint not null,
correct bool not null,
/* more fields */
foreign key (problem_id) references problems(id)
);
现在,我想要做的是以下几点:
对于每个id
在problems
,返回一行由该ID的,该问题的正确提交数量以及该问题的提交总数。
基本上,我想用下面的查询:
select
problems.id,
sum(submissions.correct),
count(submissions.id)
from submissions inner join problems
on submissions.problem_id=problems.id and problems.id=[problem_id];
其中[problem_id]
越过在problems
每id
。
看来我需要使用子查询,但我尝试了它,它根本不起作用。
如何创建一个查询来返回这些结果?
纠正我,如果我错了,但我不能只使用,而不是''之总和(s.correct)'(如果(s.correct ,1,0))'因为'true'存储为'1','false'存储为'0'? – Jashaszun
尽管我最喜欢你的答案,因为你也碰到了“左连接”点。 – Jashaszun
我尝试避免布尔类型,所以我不能回答你的问题。试试吧:) – Sebas