我正在使用Postgresql。假设我有3个表:
Classes
id | name
1 | Biology
2 | Math
Students
id | name
1 | John
2 | Jane
Student_Classes
id | student_id | class_id | registration_token
1 | 1 | 1 | abc
2 | 1 | 2 | def
3 | 2 | 1 | zxc
我想获得这样的结果集:
Results
student_name | biology | math
John | abc | def
Jane | zxc | NULL
我可以使用此查询获得此结果集:
SELECT
student.name as student_name,
biology.registration_token as biology,
math.registration_token as math
FROM
Students
LEFT JOIN (
SELECT registration_token FROM Student_Classes WHERE class_id = (
SELECT id FROM Classes WHERE name = 'Biology'
)
) AS biology
ON Students.id = biology.student_id
LEFT JOIN (
SELECT registration_token FROM Student_Classes WHERE class_id = (
SELECT id FROM Classes WHERE name = 'Math'
)
) AS math
ON Students.id = math.student_id
有没有办法在没有每个类的连接语句的情况下获得相同的结果集?有了这个解决方案,如果我想添加一个类,我需要添加另一个连接语句。
答案 0 :(得分:1)
你可以通过postgresql tablefunc扩展交叉表来完成这个,但是这样的表示要求可以在sql之外更好地处理。