大家都在下面的查询中遇到问题。我有三个字段,其中Customer_id是客户的ID,GUID是客户的全局标识符,并且有DB_Parentid字段,其中包含客户的父客户的价值(如另一家公司的母公司)。
这里尝试使用下面的子查询填充'Customer Guid字段'中的GUID字段。以下查询可以从49 k记录中运行255行。相同的查询适用于另一个客户表。
select
Customer_id as'SourceSystemID',
GUID as 'CustomerGUID',
(select a1.Customer_id from Customer a left join Customer a1 on a.DB_PARENT_ID=a1.Customer_id where a.Customer_id=Customer.Customer_id) AS 'Customer ParentGUID'
FROM dbo.Customer
答案 0 :(得分:2)
为什么要在子查询中进行连接?我认为你的意图应该只是将它与外部查询相关联:
select Customer_id as SourceSystemID,
GUID as CustomerGUID,
(select parent.Customer_id
from Customer parent
where c.DB_PARENT_ID = parent.Customer_id
) AS "Customer ParentGUID"
FROM dbo.Customer c;
我也认为最初的表述可能有倒退的逻辑,让孩子而不是父母回归。
最后,您通常会使用left outer join
:
select Customer_id as SourceSystemID,
GUID as CustomerGUID,
parent.Customer_id AS "Customer ParentGUID"
FROM Customer c left outer join
Customer parent
on c.DB_PARENT_ID = parent.Customer_id
答案 1 :(得分:1)
select a.Customer_id as'SourceSystemID',
a.GUID as 'CustomerGUID',
a1.Customer_id AS 'Customer ParentGUID'
FROM dbo.Customer a
left join Customer a1 on a.DB_PARENT_ID=a1.Customer_id