如何在此代码中的 SQL 中创建一个好的子查询

how do I make a good subquery in SQL in this code

我需要一些关于 SQL 语句的帮助,几乎是初学者所以请放轻松。

该计划要我给出每个在学校学习不到 7 年的学生

Select schoolid, characterid, firstname, lastname, count(year) as num
from schoolhouse natural join student natural join character
group by schoolid, characterid, firstname, lastname

到目前为止,非常好,通过这段代码,我已经可以看到与计算年份的关系,但我无法创建包含 select 语句中的“num”计数的 where 语句。

WHERE 子句在连接 table 之后但在连接 grouped/aggregated 之前应用于各个行。 HAVING 子句用于对聚合结果断言条件。只需添加 HAVING count(year) < 7

Select schoolid, characterid, firstname, lastname, count(year) as num
from schoolhouse natural join student natural join character
group by schoolid, characterid, firstname, lastname
having count(year) < 7

而且 始终 限定 table 您的专栏来自哪个。在此查询中,不清楚 year 列是来自 schoolhouse table、student table 还是 character table.

它应该看起来更像...

SELECT TABLE.schoolid, TABLE.characterid, TABLE.firstname, TABLE.lastname, COUNT(TABLE.year) AS num
FROM schoolhouse NATURAL JOIN student NATURAL JOIN character
GROUP BY TABLE.schoolid, TABLE.characterid, TABLE.firstname, TABLE.lastname
HAVING COUNT(TABLE.year) < 7

(将每次出现的 TABLE 替换为每个案例的正确 table 名称。)

最后,通常不赞成使用 characteryear 等词作为列或 table 名称。这些词经常作为“关键词”出现在 SQL 中,可能会导致错误或歧义。一般来说,如果 可能 作为 SQL 关键字出现,请不要将其用作列或 table名字.