gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 06:41:19 25 4
gpt4 key购买 nike

我知道问题标题可能不太清楚理解,但我尝试解释一下:

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_id 进行记录与 id 。最后我想要的是admin行数据和countproperties 。这是查询第一部分的输出:

  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 。我想要每个 admin 的所有记录来自users_table加上其 property_id 的计数。然后查询sells_table在某种程度上,对于每个 property每个admin sells的数量和 sum计算出总销量的百分比。 例如,这应该是 admin 的结果与 id 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 .

最佳答案

我想这就是你想要的:

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;

关于mysql - 查找同一个表中一行的许多匹配项,并根据结果从第二个表中获取结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51484612/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com