首页 > 解决方案 > 根据链接到表 1 的 ID 选择数据时,将表 2 中的多行连接到单独的列中?

问题描述

我可能有不正确的数据库设计,但我有如下问题:

    +-----------+        +------------+-----------+
    |  table1   |        |         table2         |
    +-----------+        +------------+-----------+
    | Type      |        | Type       | Item      |
    | Fruit     |        | Fruit      | Apple     |
    | Vegetable |        | Fruit      | Orange    |
    +-----------+        | Fruit      | Pear      |
                         | Vegetable  | Zucchini  |
                         +------------+-----------+

我想查询我的数据库以返回如下所示的内容:

+-------------+----------+----------+---------+
|     Result  |          |          |         |
+-------------+----------+----------+---------+
| Type        | Result1  | Result2  | Result3 |
| Fruit       | Apple    | Orange   | Pear    |
+-------------+----------+----------+---------+

当我根据“水果”ID 查询项目时。我当前的查询将为每个查询返回一行,但我想将这些行转换为结果表中的单独列。

我已经研究过使用不同类型的连接和 group_concat,但我认为这些都不适合作为解决方案本身。我是一个 SQL 菜鸟,所以我很难知道要寻找的“什么”。

SELECT t1.Type, t2.item,
FROM table1 as t1, table2 as t2
WHERE t2.Type="Fruit";  

我知道这将返回结果的每次迭代,但这不是我想要的。

标签: sqldatabaseduplicates

解决方案


您可以使用条件聚合:

select type,
       max(case when seqnum = 1 then item end) as item_1,
       max(case when seqnum = 2 then item end) as item_2,
       max(case when seqnum = 3 then item end) as item_3
from (select t2.*, row_number() over (partition by type order by type) as seqnum
      from table2 t2
     ) t2
where type = 'Fruit'
group by type;

请注意,这table1不是必需的,因为typetable2.


推荐阅读