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

标签 mysql sql group-by

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

相关文章:

mysql - MySQL 表中的所有数据是否也应该存储在 solr 中?

mysql - 使用 SQL 和日期进行操作

MySQL:优化 GROUP BY 多个键

php - MySQL 使用 AJAX 和 JSON 删除行失败

php - 对于以下场景,如何使用 SQL 查询显示按月结果?

具有相同 ID 的 MySQL SUM

mysql - Insert 语句中出现错误 1064,您的 SQL 语法在附近有错误

SQL 合并联合结果中的行并计算

python - pandas GroupBy 和组中前几行的累积平均值

php - PHP 和 MYSQL 中的 IM 聊天系统?