PostgreSQL中的一个简单SQL语句:
select class_offerings.semester_code as SC, class_offerings.class_code as CC,
class_offerings.class_name as CN, class_offerings.teacher_name as TN,
count(distinct class_enrollment.semester_code,
class_enrollment.class_code) as num_enrolled, --wrong
class_enrollment.maximum_capacity as max_enrollment
from class_offerings natural join class_enrollment;
PostgreSQL不支持这种语法。我该怎么做呢?预期结果:
SC | CC | CN | TN | num_enrolled | max_enrollment
答案 0 :(得分:1)
永远不要使用natural join
。这是一种憎恶,因为它取决于具有相同名称的列。它甚至没有使用正确声明的外键关系。
表别名使查询更易于编写和读取。也许你打算:
select o.semester_code as SC, o.class_code as CC, o.class_name as CN, o.teacher_name as TN,
count(*) as num_enrolled, --wrong
from class_offerings o join
class_enrollment e
on c.? = e.?
group by o.semester_code, o.class_code, o.class_name, o.teacher_name;
将联接的列放在on
所在的?
子句中。