sql查询语句执行顺序问题?

2025年03月23日 02:10
有5个网友回答
网友(1):

别名必须databse里面的实体的别名,如表 视图等,t不是是database里面实际存在的东西,from t肯定失败

网友(2):

是的,SQL当然是从第一行开始,如果你使用的查询分析器,是要把前面的删除的,如果不删除,它会执行你输入的所有内容,怎样才能看到执行过的查询语句,只能

网友(3):

如那样的,WHERE score.stuid=t.stuid 就是全部数据了,这一语法就多余了。
我改了如下,即括号里的score用另一别名m代替,以与括号外的score的别名t的区分
SELECT stuid as 学生ID
,(SELECT point FROM score as m WHERE m.stuid=t.stuid AND couid=3) AS 英语
,COUNT(*) AS 有效课程数, AVG(t.point) AS 平均成绩
FROM score AS t
GROUP BY stuid

网友(4):

t 是外层select 语句的别名,并不是内层select表的别名,所以在内层里不能使用t
外层SELECT stuid as 学生ID ,(SELECT point FROM score WHERE score.stuid=t.stuid AND couid=3) AS 英语
,COUNT(*) AS 有效课程数, AVG(t.point) AS 平均成绩
FROM score
内层 SELECT point FROM score WHERE score.stuid=t.stuid AND couid=3

网友(5):

as 后面的别名可以随便起,因为你已经有一个被as t了,所以其它的再as t就会报错,下边有个例子,有二种写法,可以看下
declare @tab table(stuid int,couid int,point int)
insert into @tab
select 1,3,80
union
select 1,4,50
union
select 1,2,80
union
select 2,3,70

SELECT t.stuid as 学生ID
,(SELECT point FROM @tab as b WHERE b.stuid=t.stuid AND couid=3) AS 英语
,COUNT(*) AS 有效课程数, AVG(t.point) AS 平均成绩
FROM @tab AS t
left join @tab b
on t.stuid=b.stuid and b.couid=3
GROUP BY t.stuid

SELECT t.stuid as 学生ID
,b.point AS 英语
,COUNT(*) AS 有效课程数
, AVG(t.point) AS 平均成绩
FROM @tab AS t
left join @tab as b
on t.stuid=b.stuid and b.couid=3
GROUP BY t.stuid,b.point
order by t.stuid