让我们说我们有表格Student,Subject和Marks表格。
结构和数据如下
CREATE MULTISET TABLE tmp_work_db.student ,FALLBACK ,
NO BEFORE JOURNAL,
NO AFTER JOURNAL,
CHECKSUM = DEFAULT,
DEFAULT MERGEBLOCKRATIO
(
student_id integer,
student_name varchar(50)
)
PRIMARY INDEX ( student_id );
insert into tmp_work_db.student
values(1,'Tim');
insert into tmp_work_db.student
values(2,'John');
insert into tmp_work_db.student
values(3,'Roy');
CREATE MULTISET TABLE tmp_work_db.subject ,FALLBACK ,
NO BEFORE JOURNAL,
NO AFTER JOURNAL,
CHECKSUM = DEFAULT,
DEFAULT MERGEBLOCKRATIO
(
subject_id integer,
subject_name varchar(50)
)
PRIMARY INDEX ( subject_id );
insert into tmp_work_db.subject
values(1,'English');
insert into tmp_work_db.subject
values(2,'Maths');
insert into tmp_work_db.subject
values(3,'Hindi');
CREATE MULTISET TABLE tmp_work_db.marks ,FALLBACK ,
NO BEFORE JOURNAL,
NO AFTER JOURNAL,
CHECKSUM = DEFAULT,
DEFAULT MERGEBLOCKRATIO
(
student_id integer,
subject_id integer,
marks integer
)
PRIMARY INDEX ( student_id,subject_id );
insert into tmp_work_db.marks
values(1,1,50);
insert into tmp_work_db.marks
values(1,2,100);
insert into tmp_work_db.marks
values(1,3,40);
insert into tmp_work_db.marks
values(2,1,50);
insert into tmp_work_db.marks
values(2,2,30);
我们需要编写一个查询,该查询将生成针对特定学科不及格的学生的报告。
我在下面的查询中尝试了让某个特定科目不及格的学生
sel student_name,subject_name,marks from tmp_work_db.student st
inner join
(
sel student_id,subject_id,marks from tmp_work_db.marks where marks < 35
) mrk
on st.student_id=mrk.student_id
inner join tmp_work_db.subject sub
on sub.subject_id=mrk.subject_id;
我无法招募未出现在特定学科中的学生。
答案 0 :(得分:1)
如果您想要的是没有为任何学科打分的学生姓名,那么您需要在cross join
和student
之间的subject
和left join
至{ {1}}:
marks
对于未能通过3个表并将条件select s.student_name, t.subject_name not_appeared
from student s cross join subject t
left join marks m
on m.student_id = s.student_id and m.subject_id = t.subject_id
where m.student_id is null
放在marks < 35
子句中的学生:
WHERE
您可以将两个查询合并为一个:
select s.student_name, t.subject_name failed
from student s
inner join marks m on m.student_id = s.student_id
inner join subject t on m.subject_id = t.subject_id
where m.marks < 35
请参见demo。
结果:
select
s.student_name, t.subject_name,
case when m.marks is null then 'not appeared' else 'failed' end result
from student s cross join subject t
left join marks m
on m.student_id = s.student_id and m.subject_id = t.subject_id
where coalesce(m.marks, 0) < 35
order by s.student_name, t.subject_name
对于组合查询:
> student_name | not_appeared
> :----------- | :-----------
> John | Hindi
> Roy | English
> Roy | Maths
> Roy | Hindi
> student_name | failed
> :----------- | :-----
> John | Maths