代码之家  ›  专栏  ›  技术社区  ›  DevMan

查找同一表中一行的多个匹配项,并根据结果从第二个表中获取结果

  •  0
  • DevMan  · 技术社区  · 7 年前

    我知道问题的标题可能不太清楚,我想解释一下:

    users_table:
    
    id | name | admin   | property_id
    -----------------------------------
     1  | x    | 1       | 0
     2  | y    | 1       | 0
     3  | z    | 0       | 1
     5  | t    | 0       | 2
     6  | u    | 0       | 2
     7  | o    | 0       | 2
    

    users_table 有两个或多个记录 admin 还有属于其中一个的其他记录 管理员 通过匹配记录 property_id id . 最后我想要的是 管理员 行数据和 count properties . 这是查询第一部分的输出:

      id | name | admin   | property_count
    -----------------------------------
      1  | x    | 1       | 1
      2  | y    | 1       | 3
    

    到目前为止,我知道如何获得所需的结果,但问题就在这里开始了,我还有另一张表

    sells_table:
    
    id | seller_id | sell_amount
    ----------------------------
     1 | 3         | 250
     2 | 5         | 120
     3 | 7         | 100
     4 | 5         | 200
    

    这就是逻辑:每 管理员 有很多 属性 每个 property 有很多 sells . 我想要每个的所有记录 管理员 来自 用户表 加上它的计数 属性\u id . 然后查询 sells_table 在某种程度上,每个 财产 每个 管理员 数量 以及 sum 总销售额的计算。 例如,这应该是 管理员 id 2 以及 name y :

      name | properties | property_sells | property_amount
      --------------------------------------------------------
       y   |    3       |     3          |   420
    

    y 3 properties . 属性 id 5 属于 y(admin) two id 7 也属于 Y(管理员) one 销售和 总和 其中 3 sells is 420 .

    我知道这不是很复杂,但解释的方法也不是那么简单。 我乐于接受编辑和提问。 事先谢谢。

    2 回复  |  直到 7 年前
        1
  •  1
  •   Gordon Linoff    7 年前

    我想这就是你想要的:

    select ua.id, ua.name, ua.admin, count(distinct u.id) as property_count,
           sum(s.sell_amount) as amount
    from users_table ua left join
         users_table u
         on ua.id = u.property_id left join
         sales s
         on s.seller_id = u.id
    where ua.admin = 1
    group by ua.id, ua.name, ua.admin;
    
        2
  •  1
  •   Alex    7 年前

    http://sqlfiddle.com/#!9/36834d/2

    SELECT u.id, U.name, u.admin, COUNT(DISTINCT ut.id) property_count, SUM(st.sell_amount)
    FROM users_table u
    LEFT JOIN users_table ut
    ON u.id = ut.property_id
    LEFT JOIN sells_table st
    ON ut.id  = st.seller_id
    WHERE u.admin = 1
    GROUP BY u.id, u.admin, u.name