繁体   English   中英

根据链接到表1的ID选择数据时,将表2中的多行连接到单独的列中?

[英]Join multiple rows from Table 2 into separate columns when selecting data based on ID linked to table 1?

我的数据库设计可能不正确,但是存在以下问题:

    +-----------+        +------------+-----------+
    |  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";  

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

您可以使用条件聚合:

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;

注意,因为typetable2 ,所以不需要table1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM