0

我查询我的数据库以从不同的表中提取一些信息。我已经设法得到一个可以接受的结果,我可能会在 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

我想GROUP BY product_id,但保持分开person_idperson_address如果person_type=0。然后连接所有person_id共享相同的地址product_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_id那些并连接它们,连接,并只保留一个。结果应如下表所示:person_type=0product_idperson_addressother_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_id没有person_address.

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

4

1 回答 1

0
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

于 2013-09-29T09:15:07.533 回答