这里重复两次子查询,
(select count(*) from hindi2_MOVIE as yaar where yaar.year = M.year)
,我不想做,有没有办法重用它们,只需运行一次查询?
我需要找到总计数,说出按年份分组的条目“tot”,然后是其他一些功能的百分比,其中分母是总计数“tot”。在下面的SQL查询中,我重复了两次select操作,我知道这是非常昂贵的,无论如何都要重用它?
select M.year,
(select count(*)
from hindi2_MOVIE as yaar
where yaar.year = M.year) as tot,
count(M.title)/(select count(*)
from hindi2_MOVIE as yaar
where yaar.year = M.year)*100 as perc
from hindi2_MOVIE AS M
where not exists (select *
from hindi2_M_CAST AS C,hindi2_PERSON AS P
where C.PID=P.PID AND C.MID=M.MID AND P.Gender='M') and
exists(select *
from hindi2_M_CAST AS C,hindi2_PERSON AS P
where C.PID=P.PID AND
C.MID=M.MID and Gender='F')
group by M.year;
答案 0 :(得分:1)
您可以使用“@”符号对查询结果进行别名,并将其用于同一查询中的任何位置
select M.year, @tot:= (select count(*) from hindi2_MOVIE as yaar where
yaar.year = M.year),count(M.title)/(@tot)*100 as perc from hindi2_MOVIE AS M
where not exists (select * from hindi2_M_CAST AS C,hindi2_PERSON AS P where
C.PID=P.PID AND C.MID=M.MID AND P.Gender='M') and exists(select * from
hindi2_M_CAST AS C,hindi2_PERSON AS P where C.PID=P.PID AND C.MID=M.MID
and Gender='F') group by M.year;
答案 1 :(得分:0)
您的查询对我来说有点混乱。 但我建议你这样编写查询。这可能行不通。但请使用以下建议。
永远不要使用Count(*),使用count(字段); 您可以通过正确使用内部联接来评估自己的差异。 永远不要使用IN或Exists,使用内部连接或左连接和条件;
示例:
选择计数(M.year)为tot,计数(M.title)/计数(M.year)* 100为perc
来自hindi2_MOVIE M.
左连接hindi2_M_CAST C on(M.SomeField = C.someField)AND C.MID = M.MID和P.Gender =' M' - (这是不存在的)
内部联接hindi2_PERSON P on C.PID = P.PID AND C.MID = M.MID and Gender =' F'
其中yaar.year = M.year和一些条件;