通过不工作查询聚合,子查询和组

时间:2017-09-20 17:34:17

标签: mysql sql

你能帮助我吗?我花了大约2个小时来理解错误,但仍然没有。

  

SQLSTATE [42S21]:列已存在:1060重复的列名   ' ID'

select t.*,
    exp(sum(ln(c)) over (order by date_col)) column_1
from (
    select t.*,
        case when row_number() over (order by date) = 1 then 100 else column_2 end as c
    from your_table t
    ) t

请不要问我到底发生了什么事。此查询的最大部分由Laravel生成。

如果删除此部分:

  

,其中   (cities.alias IN(SELECT select count(*) as aggregate from ( select `cities`.*, `cities`.`id` as `id`, `cities`.`country_id` as `country_id`, `cities`.`name` as `name`, `cities`.`alias` as `alias`, `cities`.`active_frontend` as `active_frontend` from `cities` where ( cities.alias in ( select `alias` from `cities` group by `alias` having COUNT(`alias`) > 1 ) ) ) count_row_table FROM alias GROUP BY cities HAVING   COUNT(alias)> 1))

它会起作用。但我需要这部分。

2 个答案:

答案 0 :(得分:0)

问题在于cities.*

但您可以将查询简化为:

select sum(cnt) as cnt
from (
    select COUNT(alias) as cnt
    from cities
    group by alias
    having COUNT(alias) > 1
    ) t

并避免重新读取您的表,因为最后,您需要的是别名有多行的总行数。

答案 1 :(得分:0)

您不需要为此实现子查询。你可以这样做:

select count(*)
from cities c
where exists (select 1 from cities c2 where c2.alias = c.alias and c2.id <> c.id);

使用cities(alias, id)上的索引,这应该会有更好的效果。