我正在尝试加入3个表 - CurrentProducts,SalesInvoice和SalesInvoiceDetail。 SalesInvoiceDetail包含其他两个表和其他一些列的FK /外键。第一个查询是可以的,但第二个查询不是。我的问题出现在代码的末尾。
右
select *
from CurrentProducts inner join
(dbo.SalesInvoiceDetail inner join dbo.SalesInvoice
on dbo.SalesInvoiceDetail.InvoiceID = dbo.SalesInvoice.InvoiceID
)
on dbo.SalesInvoiceDetail.ProductID = dbo.CurrentProducts.ProductID
错误
select *
from CurrentProducts inner join
(select * from
dbo.SalesInvoiceDetail inner join dbo.SalesInvoice
on dbo.SalesInvoiceDetail.InvoiceID = dbo.SalesInvoice.InvoiceID
)
on dbo.SalesInvoiceDetail.ProductID = dbo.CurrentProducts.ProductID
错误 - 关键字“on”附近的语法不正确。
为什么第二个查询错了?它在概念上与第一个不一样吗?这是内部连接产生结果集。我们选择*结果集,然后将此结果集加入CurrentProducts?
答案 0 :(得分:1)
您需要为内部查询设置别名。另外,在第一个中不需要括号。
select *
from CurrentProducts inner join
(select * from
dbo.SalesInvoiceDetail inner join dbo.SalesInvoice
on dbo.SalesInvoiceDetail.InvoiceID = dbo.SalesInvoice.InvoiceID
) A
on A.ProductID = dbo.CurrentProducts.ProductID
答案 1 :(得分:1)
第一个查询是使用较旧语法表示的“普通”连接。它可以改写为:
select
*
from
CurrentProducts
inner join dbo.SalesInvoiceDetail
on dbo.SalesInvoiceDetail.ProductID = dbo.CurrentProducts.ProductID
inner join dbo.SalesInvoice
on dbo.SalesInvoiceDetail.InvoiceID = dbo.SalesInvoice.InvoiceID
第二个查询是第二个表是子查询的连接。当您加入子查询时,必须为其分配别名并使用该别名来引用子查询返回的列:
select
*
from
CurrentProducts
inner join (select *
from dbo.SalesInvoiceDetail
inner join dbo.SalesInvoice
on SalesInvoiceDetail.InvoiceID = SalesInvoice.InvoiceID
) as foo on foo.ProductID = dbo.CurrentProducts.ProductID