【问题标题】:Return multiple columns in SQL consult在 SQL 咨询中返回多列
【发布时间】:2020-10-21 14:38:22
【问题描述】:

我需要创建一个查询来返回同一个表中的多个值,并将其作为结果的列返回,例如:

在此表中,路径值不同,但可以具有相同的 id_location。

SELECT
    Name,
    Address,
    path
from
    `table_location` as A
inner JOIN table_images as B
on A.id = B.id_location

where A.des

这次回归

test1, example, pathExample1
test1, example, pathExample2
test3, example, pathExample3
test3, example, pathExample4

如何在列中返回路径?

例子:

test1, example, pathExample1, pathExample2
test3, example, pathExample3, pathExample4

我该怎么做?

【问题讨论】:

    标签: mysql sql pivot


    【解决方案1】:

    您可以使用group_concat()

    SELECT
        Name,
        Address,
        group_concat(path) as path
    from
        `table_location` as A
    inner JOIN table_images as B
    on A.id = B.id_location
    group by Name,Address
    

    【讨论】:

      【解决方案2】:

      最简单的方法是使用group_concat()

      select name, address, group_concat(path) as paths
      from table_location l join
           table_images i
           on l.id = i.id_location
      where A.des
      group by name, address;
      

      这会将结果放入单个列中。如果你想要两列,那么你可以使用:

      select name, address, min(path), nullif(max(path), min(path))
      from table_location l join
           table_images i
           on l.id = i.id_location
      where A.des
      group by name, address;
      

      【讨论】:

        【解决方案3】:

        据我了解,问题是如何将每个位置的图像旋转到不同的列。

        如果你事先知道每个位置的最大图像数量,你可以做如下条件聚合:

        select l.name, l.address,
            max(case when i.rn = 1 then i.path end) path1,
            max(case when i.rn = 2 then i.path end) path2,
            max(case when i.rn = 3 then i.path end) path3
        from table_location l
        inner join (
            select i.*, row_number() over(partition by id_location order by path) rn
            from table_images i
        ) i on i.id_location_id = l.id
        group by l.id
        

        您可以向select 子句添加更多条件表达式,以处理每个位置的更多图像。

        请注意,row_number() 仅在 MySQL 8.0 中可用。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-10-02
          • 1970-01-01
          • 1970-01-01
          • 2019-12-27
          • 2019-09-26
          • 1970-01-01
          • 1970-01-01
          • 2017-05-21
          相关资源
          最近更新 更多