我有4张这样的表
学生表
-----------------------
|id_student | name |
|1 | John |
|2 | Michael |
-----------------------
电话号码表
--------------------------------------
|id_phone | phone_number | id_student |
| 1 | +612823888 | 1 |
| 2 | +612823723 | 1 |
| 3 | +612123123 | 2 |
| 4 | +613432322 | 2 |
---------------------------------------
课程表
____________________
|id_course | course |
|1 | Math |
|2 | Science |
|3 | Art |
|__________|_________|
参加课程表
__________________________________
|id_take | id_student | id_course |
|1 | 1 | 1 |
|2 | 1 | 2 |
|3 | 1 | 3 |
|4 | 2 | 1 |
|________|____________|___________|
===查看我的预期====
_________________________________
|name |phone |course |
|John | +6128238883 | Math |
|John | +6128237237 | Science |
|John | - | Art |
|Michael | +612123123 | Math |
|Michael | +613432322 | - |
|________|_____________|_________|
我创建的SQL语法:
SELECT student.name, phone.phone_number, course.course_name FROM student
JOIN phone ON phone.id_student = student.id_student
JOIN take_course ON take_course.id_student = student.id_student
JOIN course ON course.id_course = take_course.id_course
JOIN表有问题,因为phone_number表只是加入student_table并且会在表I中重复预期。什么是正确的SQL语法来创建这样的视图?
答案 0 :(得分:1)
使用row_number()生成序列ID,然后在手机上使用FULL OUTER JOIN,然后选择课程/课程ON id_student& "序列ID"
select s.name, pc.phone_number, pc.course
from Student s
inner join
(
select id_student = coalesce(p.id_student, c.id_student),
p.phone_number,
c.course
from
(
select p.id_student, p.phone_number,
-- id is the new sequence id
id = row_number() over (partition by p.id_student
order by p.id_phone)
from Phone_Number p
) p
full outer join
(
select t.id_student, c.course,
-- id is the new sequence id
id = row_number() over (partition by t.id_student
order by c.id_course)
from Take_Course t
inner join Course c on t.id_course = c.id_course
) c on p.id_student = c.id_student
and p.id = c.id
) pc on s.id_student = pc.id_student
order by s.name