我正在为课程进行一些SQL练习。对于一个查询,我在FROM子句中创建一个表,然后在我的WHERE和SELECT子句中引用它。据我所知,这不应该导致问题,因为SQL评估顺序是FROM - >在哪里 - >选择。但是,MS Access给出了以下错误:
“Microsoft Access数据库引擎找不到输入表或查询'Totals'。确保它存在并且其名称拼写正确。”
有人看到我的查询有问题吗?
以下是可用的表格:
以下是练习题:
以下是我的回答:
SELECT DISTINCT Totals.sname
FROM ( SELECT S.sname, COUNT(*) as Num
FROM Student S, Enrolled E, Class C
WHERE S.snum = E.snum AND E.cname = C.cname
GROUP BY S.snum, S.sname ) AS Totals
WHERE Totals.Num = (SELECT MAX(Totals.Num) FROM Totals)
编辑:William Burnham正确指出问题出在WHERE子句中。似乎子查询无法访问“总计”表。这是SQL的限制(或者可能是MS Access的SQL版本),还是有办法从WHERE子句中的子查询访问“总计”表?
答案 0 :(得分:2)
我想你可以尝试这样的事情:
SELECT S.sname
FROM Student S join Enrolled e on S.snum=e.snum
GROUP BY S.sname
HAVING COUNT s.snum= MAX(SELECT COUNT(e1.snum)
FROM Enrolled e1 join Class c on e1.cname=c.cname)
答案 1 :(得分:0)
不确定,但我认为你不能在这样的where子句中进行子选择。 试试这个:
WITH Totals(sname, Num) as (
SELECT S.sname, COUNT(*) as Num
FROM Student S
join Enrolled E on S.snum = E.snum
join Class C on E.cname = C.cname
GROUP BY S.sname
)
SELECT DISTINCT t.sname
FROM Totals t
WHERE t.Num = (SELECT MAX(t1.Num) FROM Totals t1)