Sql 根据链接到表1的ID选择数据时,是否将表2中的多行合并到单独的列中?
我可能有不正确的数据库设计,但我有一个问题如下:Sql 根据链接到表1的ID选择数据时,是否将表2中的多行合并到单独的列中?,sql,database,duplicates,Sql,Database,Duplicates,我可能有不正确的数据库设计,但我有一个问题如下: +-----------+ +------------+-----------+ | table1 | | table2 | +-----------+ +------------+-----------+ | Type | | Type | Item | | Fruit |
+-----------+ +------------+-----------+
| 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;
请注意,不需要table1
,因为type
位于table2
中,请考虑要在应用程序中处理的数据显示“问题”。。