【问题标题】:Multiple counts on same table in mysqlmysql中同一张表的多次计数
【发布时间】:2014-03-20 13:33:24
【问题描述】:

这里重复子查询两次,

(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;

【问题讨论】:

  • 为什么不能使用tot作为变量:count(M.title)/tot * 100 as perc
  • @SamuelCook 它给了我错误。Unknown column 'tot' in 'field list'

标签: mysql sql


【解决方案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;

【讨论】:

    【解决方案2】:

    您的查询对我来说有点令人困惑。 但我建议您像这样编写查询。这可能行不通。但请使用以下建议。

    永远不要使用 Count(*),使用 count(field); 您可以通过正确使用内部连接自行评估差异。 永远不要使用 IN 或 Exists,适当和条件使用内连接或左连接;

    例子:

    选择 count(M.year) 作为 tot,count(M.title)/count(M.year) *100 作为 perc
    来自hindi2_MOVIE M left join Hindi2_M_CAST C on (M.SomeField = C.someField) AND C.MID=M.MID and P.Gender='M' -- (这是不存在的) 在 C.PID=P.PID AND C.MID=M.MID 和 Gender='F' 上的内部连接hindi2_PERSON P 其中 yaar.year = M.year 和一些条件;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-18
      • 2016-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      相关资源
      最近更新 更多