gpt4 book ai didi

mysql - SQL - 'partial' 分组依据,不同列的不同行为

转载 作者:行者123 更新时间:2023-11-30 01:15:41 25 4
gpt4 key购买 nike

我查询数据库以从不同的表中提取一些信息。我已经设法得到了一个可以接受的结果,我可以在 SQL 之外使用它。我得到的结果效率非常低,我想知道是否有办法让 SQL 完成一些工作。基本上,我需要更有效地对数据进行分组并丢弃其中一些。

我当前的查询结果是一个表,可以简化如下:

product_id | person_id | person_type | person_address | other_column
1 | 1001 | 1 | 999 Main St | info about product 1
1 | 1245 | 0 | | info about product 1
1 | 5133 | 2 | 101 Sql St | info about product 1
1 | 9191 | 0 | 1 Query Ave | info about product 1
2 | 5451 | 1 | 40 Table Rd | info about product 2
2 | 6610 | 0 | | info about product 2

我想按product_id分组,但如果person_type=0,则保留单独的person_idperson_address。然后连接共享相同 product_id 的所有 person_id 的地址。仅保留 other_column 中的一个值。如果应用到上表中,它应该看起来像这样:

product_id | person_id | person_address |                        other_address | other_column
1 | 1245 | | 999 Main St; 101 Sql St; 1 Query Ave | info about product 1
1 | 9191 | 1 Query Ave | 999 Main St; 101 Sql St | info about product 1
2 | 6610 | | 40 Table Rd | info about product 2

--

或者,第二好的解决方案如下:GROUP BY Product_id,保留具有 person_type=0person_id 并在多个共享相同 product_id 的情况下将它们连接起来>,连接 person_address,并仅保留一个 other_column。结果应如下表所示:

product_id |  person_id |                       person_address | other_column
1 | 1245; 9191 | 999 Main St; 101 Sql St; 1 Query Ave | info about product 1
2 | 6610 | 40 Table Rd | info about product 2

--

为了提供一些背景知识,我有两个目标:第一个目标是提取 other_column 但丢弃不必要的重复项。它是文本信息,所以相当重。第二个目标是能够获取那些没有 person_addressperson_id一些位置信息。

(我尝试搜索类似的问题,但没有找到任何内容。)

最佳答案

select
t1.product_id, t1.person_id,
t1.person_address,
group_concat(t2.person_address) as other_address
from Table1 as t1
left outer join Table1 as t2 on
t2.product_id = t1.product_id and t2.person_id <> t1.person_id
where t1.person_type = 0
group by t1.product_id, t1.person_id

sql fiddle demo

关于mysql - SQL - 'partial' 分组依据,不同列的不同行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19076166/

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