gpt4 book ai didi

sql - select 语句可以包含嵌套结果集吗?

转载 作者:行者123 更新时间:2023-12-02 11:14:34 25 4
gpt4 key购买 nike

给出下表和示例数据:

create table Orders (
ID int not null primary key,
Customer nvarchar(100) not null);

create table OrderItems (
ID int not null primary key,
OrderID int not null foreign key references Orders(ID),
Product nvarchar(100) not null);

insert into Orders values (1, 'John');
insert into Orders values (2, 'James');
insert into OrderItems values (1, 1, 'Guitar');
insert into OrderItems values (2, 1, 'Bass');
insert into OrderItems values (3, 2, 'Guitar');
insert into OrderItems values (4, 2, 'Drums');

我想知道是否可以查询父 Orders 表,并获取子 OrderItems 表作为父结果中的嵌套结果集。像这样的事情:

| ORDER.ID | ORDER.CUSTOMER | ORDER.ORDERITEMS                   |
------------------------------------------------------------------
| | | ORDERITEMS.ID | ORDERITEMS.PRODUCT |
| | |-------------------------------------
| 1 | John | 1 | Guitar |
| | | 2 | Bass |
| 2 | James | 3 | Guitar |
| | | 4 | Drums |

我想到的查询(在 SQL Server 中不起作用)是这样的:

-- doesn't work, but shows the intent to have nested result sets
select
o.OrderID [Order.ID], o.Customer [Order.Customer],
(select
oi.ID [OrderItems.ID], oi.Product [OrderItems.Product]
from OrderItems oi where o.ID = oi.OrderID
) [Order.OrderItems]
from Orders o;

这只是一个概念性问题,因为我正在尝试寻找以最少重复的方式获取相关数据的方法(例如,与 join 所发生的情况相反)。

SQL fiddle here .

更新

我从this answer得知Oracle 通过游标表达式支持它:

select 
o.*,
cursor(select oi.* from OrderItems oi where o.ID = oi.OrderID) as OrderItems
from Orders o;

最佳答案

没有。这实际上是不可能的。

SQL Server 不支持嵌套关系和 NF²

尽管您可以使用FOR XML PATH以分层方式将其恢复。

SELECT ID       AS [@ID],
Customer AS [@Customer],
(SELECT ID AS [@ID],
OrderID AS [@OrderID],
Product AS [@Product]
FROM OrderItems
WHERE OrderItems.OrderID = o.ID
FOR XML PATH('OrderItems'), TYPE)
FROM Orders o
FOR XML PATH('Order'), ROOT('Orders')

返回

   <Orders>
<Order ID="1" Customer="John">
<OrderItems ID="1" OrderID="1" Product="Guitar" />
<OrderItems ID="2" OrderID="1" Product="Bass" />
</Order>
<Order ID="2" Customer="James">
<OrderItems ID="3" OrderID="2" Product="Guitar" />
<OrderItems ID="4" OrderID="2" Product="Drums" />
</Order>
</Orders>

这不会重复父订单

关于sql - select 语句可以包含嵌套结果集吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15748497/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com