我正在写一个SQL查询,但仍然遇到同样的错误,并且不知道如何解决它。
select k.klantnr, aantal
from klanten k INNER JOIN(
select d.klantnr, count(d.reisnr) as aantal
from deelnames d
where k.klantnr = d.klantnr
group by d.klantnr) as adeelnames USING(klantnr)
错误:
There is an entry for table "k", but it cannot be referenced from this part of the query.
答案 0 :(得分:1)
子查询中不需要关联子句:
select klantnr, aantal
from klanten k INNER JOIN
(select d.klantnr, count(d.reisnr) as aantal
from deelnames d
group by d.klantnr
) adeelnames
USING (klantnr);
USING
子句可以满足您的所有需求。请注意,k.
中也移除了SELECT
。
此外,如果您希望计数为0,则可能需要LEFT JOIN
。
答案 1 :(得分:1)
假设klatnr在klanten中的唯一键中,您应该只能使用连接并跳过派生表:
select k.klantnr, count(d.reisnr) as aantal
from klanten k join deelnames d using(klantnr)
group by k.klantnr;