将select输出作为where子句中的表引用

时间:2017-01-13 12:52:27

标签: mysql sql database

我有一个查询,我想执行像

这样的操作
select *
from (query which i wrote) as x
where
 (select count(*)
  from x as y
  where x.location=y.location
  and x.count>=y.count)<=3;

提供错误

而不是x,我可以添加我写的查询。但查询非常大。当我尝试上面的查询时,它给出的表不存在错误。有没有办法执行上述操作?请帮助我。

1 个答案:

答案 0 :(得分:0)

您不能重复使用这样的表别名。相反,您需要复制子查询。或者使用变量:

select q.*
from (select q.*,
             (@rn := if(@l = location, @rn + 1,
                        if(@l := location, 1, 1)
                       )
             ) as rn
      from (query which i wrote) q cross join
           (select @l := '' , @rn := 0) params
      order by location, count desc
     ) q
where rn <= 3;