为什么相关子查询的结果不能用于外层查询?

Why correlated subquery result cannot be used in outer query?

为什么关联子查询的结果不能用于外层查询?

在下面的查询中,我想在外部查询中访问内部相关查询中的计数。但它给出了错误。

我做错了什么?

引用 - http://sqlzoo.net/wiki/More_JOIN_operations#Looking_at_the_id_field.

问题 - 14(获得至少担任过 30 位主演的演员的字母顺序列表。)

select distinct a.name  , t.count
from actor a 
join casting c 
on (a.id= c.actorid) 
where 25< (select count(movieid) as count 
    from casting c1 
    where c1.actorid= a.id) as t
order by a.name

下面的查询工作正常。

select distinct a.name, (select count(movieid) as count 
    from casting c1 
    where c1.actorid= a.id)
from   actor a 
join casting c 
on (a.id= c.actorid) 

http://sqlfiddle.com/#!4/4e7be/8

count 是子查询中的一列,但它不是外连接的一部分。因此,它在子查询本身之外是不可见的。

解决这个问题的一种更简单的方法是计算连接本身的计数,如下所示:

select a.name, count(movieid)
from
actor a 
join casting c
on a.id = c.actorid
group by a.name, a.id
having count(movieid) > 3
order by a.name;

SQL Fiddle

问题是问两件事。一个是主演,两个是至少 30 次。您可以使用 WHERE 解决第一个问题,然后将结果分组以进行计数。最后用HAVING过滤第二题

您可以在HAVING 语句中使用COUNT 函数。

SELECT actor.name
 FROM actor JOIN casting ON actor.id = casting.actorid
 WHERE ord = 1
 GROUP BY actor.name
 HAVING COUNT(actor.name) >= 30
 ORDER BY actor.name 

SELECT姓名 FROM 演员 JOIN actor.id=casting.actorid WHERE 顺序=1 GROUP BY 名字 HAVING COUNT(电影编号)>=30

SELECT 姓名 来自演员 JOIN casting ON (id = actorid AND (SELECT COUNT(ord) FROM casting WHERE actorid = actor.id AND ord=1)>=30) 按名称分组

对我来说这很好用:

select actor.name
from actor
join casting on casting.actorid=actor.id
join movie on casting.movieid=movie.id
where casting.ord=1
group by actor.name
having count(actor.name) > 29
order by actor.name