我有应查询表达式并显示它的SQL查询
这是查询
SELECT (classes.amount_of_students - (SELECT COUNT(id_class) FROM classes_students WHERE id_class = 1)) AS free_playces FROM classes INNER JOIN classes_students ON classes.id_class = classes_students.id_class;
以下是表格:
CREATE TABLE classes_students (
id_class SERIAL REFERENCES classes (id_class),
id_student SERIAL REFERENCES student (id_student),
PRIMARY KEY (id_class, id_student)
);
CREATE TABLE classes (
id_class SERIAL PRIMARY KEY,
amount_of_hours VARCHAR NOT NULL,
amount_of_students VARCHAR NOT NULL,
id_subject SERIAL REFERENCES subject (id_subject),
id_teacher SERIAL REFERENCES teacher (id_teacher)
);
classes
表中的数据:
id_class | amount_of_hours | amount_of_students | id_subject | id_teacher
----------+-----------------+--------------------+------------+------------
1 | 180 | 9 | 1 | 2
2 | 12 | 9 | 2 | 1
还有classes_students
:
id_class | id_student
----------+------------
1 | 1
2 | 2
1 | 3
结果是:
`
7
7
7
`
我不明白为什么要播三遍。我只需要展示一次。我该如何解决这个问题以及为什么会发生呢?我添加了与众不同的内容,但我认为这不是最佳解决方案。
答案 0 :(得分:0)
外部查询中不需要JOIN
。同样,您应该将内部查询中的类与外部查询中的类进行匹配。这称为相关子查询:
SELECT (c.amount_of_students -
(SELECT COUNT(id_class)
FROM classes_students cs
WHERE cs.id_class = c.id_class
)
) as free_places
FROM classes c
WHERE c.id_class = 1