发现很多场比赛,一列在同一个表,并根据结果从第二个表得到结果(Finding many matche

2019-11-05 00:51发布

我知道问题的标题可能不会退出清楚理解,但我试图解释:

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和属于其中的一个部分其他记录admin由匹配记录property_idid 。 到底是什么我想的是admin行数据和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

因此,这是逻辑:每个admin有很多properties ,并且每个property有许多sells 。 我想每一个所有记录adminusers_table加上它的计数property_id 。 然后查询sells_table在对每个办法property每个admin的数量sellssum总量的主要销售被计算。 例如,这应该是结果adminid 2name y

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

y3 properties 。 与属性id 5属于y(admin)具有two sellsid 7这也属于y(admin)具有one出入和sum的这些3 sells is 420

我知道这是不是很复杂,但解释它的方法是不那么容易。 我打开的编辑和问题。 提前致谢。

Answer 1:

我认为这是你想要什么:

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;


Answer 2:

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


文章来源: Finding many matches to one row in the same table and getting results from a second table based on the results
标签: mysql sql mysqli