[英]Join multiple rows from Table 2 into separate columns when selecting data based on ID linked to table 1?
I may have the incorrect database design, but I have an issue as follows: 我的数据库设计可能不正确,但是存在以下问题:
+-----------+ +------------+-----------+
| table1 | | table2 |
+-----------+ +------------+-----------+
| Type | | Type | Item |
| Fruit | | Fruit | Apple |
| Vegetable | | Fruit | Orange |
+-----------+ | Fruit | Pear |
| Vegetable | Zucchini |
+------------+-----------+
I would like to query my DB to return something that looks like this: 我想查询我的数据库以返回如下所示的内容:
+-------------+----------+----------+---------+
| Result | | | |
+-------------+----------+----------+---------+
| Type | Result1 | Result2 | Result3 |
| Fruit | Apple | Orange | Pear |
+-------------+----------+----------+---------+
When I query items based on the "Fruit" ID. 当我基于“水果” ID查询项目时。 My current query will return a row for each, but I'd like to turn these rows into separate columns in the results table.
我当前的查询将为每个查询返回一行,但我想将这些行转换为结果表中的单独列。
I've looked around into using different types of joins and group_concat, but I don't think any of these are explicitly appropriate as a solution by itself. 我已经研究了使用不同类型的联接和group_concat的方法,但是我认为这些方法本身都不适合作为解决方案。 I'm a bit of an SQL rookie so I'm having trouble on knowing "what" to look for.
我有点像SQL新手,所以在知道要查找的内容方面遇到了麻烦。
SELECT t1.Type, t2.item,
FROM table1 as t1, table2 as t2
WHERE t2.Type="Fruit";
I understand that this will return each iteration of the results, but is not what I want. 我知道这将返回结果的每次迭代,但这不是我想要的。
You can use conditional aggregation: 您可以使用条件聚合:
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;
Note that table1
is not needed because type
is in table2
. 注意,因为
type
在table2
,所以不需要table1
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.