代码之家  ›  专栏  ›  技术社区  ›  Satyajeet Kanetkar

如何将多层父表与中间父表上的“GROUP BY”连接起来?

  •  0
  • Satyajeet Kanetkar  · 技术社区  · 6 年前

    我有一个类似的结构:

    country:  | state:         | city:        | citizen:
        id    |    id          |    id        |    id
        name  |    name        |    name      |    age
              |    country_id  |    state_id  |    city_id
              |                |              |    
    

    我需要的结果如下:

    country_name | state_name  | city_name | citizens
    ----------------------------------------------------
    India        | MH          | Mumbai    | 45
    USA          | California  | LA        | 234 
    USA          | Washington  | Seattle   | 324
    

    我尝试的查询是:

    SELECT 
        country.name AS "country_name",
        state.name AS "state_name",
        city.name AS "city_name",
        count(citizen.id) AS "citizens"
    FROM citizen
    LEFT JOIN city on citizen.city_id = city.id
    LEFT JOIN state on city.state_id = state.id
    LEFT JOIN country on state.country_id = country.id
    WHERE 
         citizen.age > 50
    GROUP BY city_name;
    

    Postgres给我的错误是:

    ERROR:  column "state.name" must appear in the GROUP BY clause
            or be used in an aggregate function
    LINE 3: state.name AS "state_name",
    

    我不确定如何实现我所需要的。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Yogesh Sharma    6 年前

    我会单独做这件事 joins

    select cn.name as country_name, st.name as state_name, 
           ct.name as city_name, c.citizens
    from (
         select city_id, count(*) as citizens
         from citizen
         where age > 50
         group by city_id
    ) c left join city ct on ct.id  = c.city_id
    left join state st on st.id = ct.state_id
    left join country cn on cn.id = st.country_id;