简体   繁体   English

如何在子查询 SQL Server 中使用 Left Join?

[英]How to use Left Join in subquery SQL Server?

I am trying to use left join in subquery in SQL Server.我正在尝试在 SQL Server 的子查询中使用左连接。 My query looks fine to me but it gives syntax error.我的查询对我来说很好,但它给出了语法错误。

This is my query:这是我的查询:

(
SELECT 
    FK_OrderNo AS LHNo, VendorName AS LHVendor
FROM 
    tbl_ShipmentAPAR 
LEFT JOIN
    tbl_vendors ON FK_VendorID = VendorID
WHERE
    FK_ServiceID = 'LH'
) LHBase ON PK_OrderNo = LHNo 
LEFT JOIN 
    (SELECT
         FK_OrderNo AS DANo,
         VendorName AS DAVendor
     FROM 
         tbl_ShipmentAPAR 
     LEFT JOIN 
         tbl_vendors ON FK_VendorId = VendorId
     WHERE 
         FK_ServiceId = 'DA') DABase ON PK_OrderNo = DANo

This is the error I'm getting:这是我得到的错误:

在此处输入图片说明

This is my table structure:这是我的表结构:

CREATE TABLE tbl_ShipmentAPAR 
(
     VendorID int PRIMARY KEY,
     VendorName varchar(200), 
     FK_OrderNo int 
)

CREATE TABLE tbl_vendors
(
     FK_VendorID int, 
     FOREIGN KEY (FK_VendorID) REFERENCES tbl_ShipmentAPAR(VendorID), 
     FK_ServiceID varchar(200)
)

INSERT INTO tbl_ShipmentAPAR VALUES (1, 'John',123)
INSERT INTO tbl_vendors VALUES (1,'LH')

As @Chris mentioned, the query is bit incomplete.正如@Chris 提到的,查询有点不完整。 I guess you are trying to do something like this:我猜你正在尝试做这样的事情:

SELECT * FROM    /*--> Added new */
(
SELECT 
    FK_OrderNo AS LHNo, VendorName AS LHVendor
FROM 
    tbl_ShipmentAPAR
LEFT JOIN
    tbl_vendors ON FK_VendorID = VendorID
WHERE
    FK_ServiceID = 'LH'
) LHBase
LEFT JOIN 
    (SELECT
         FK_OrderNo AS DANo,
         VendorName AS DAVendor
     FROM 
         tbl_ShipmentAPAR 
     LEFT JOIN 
         tbl_vendors ON FK_VendorId = VendorId
     WHERE 
         FK_ServiceId = 'DA') DABase ON LHBase.LHNo = DABase.DANo /* -->Modified PKOrder no to LHNo because PKOrder no doesn't exist in either of the sub-queries */

This query worked for me.这个查询对我有用。 Comment to this answer if something must be changed.如果必须更改某些内容,请对此答案发表评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM