给定下表和示例数据:
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
例如,与 a 会发生的情况相反)。
SQL Fiddle在这里。
更新
我从这个答案中发现 Oracle 使用游标表达式支持它:
select
o.*,
cursor(select oi.* from OrderItems oi where o.ID = oi.OrderID) as OrderItems
from Orders o;