我在加入本地表和链接服务器表时遇到问题。我只能通过使用内部联接来完成它,但它花了太长时间来执行查询。 我知道有一种方法可以通过OPENQUERY来实现,但我无法得到它。
这是我在开始时所做的事情:
SELECT DISTINCT
local.L_ID
FROM dbo.local_table AS local
INNER JOIN [server].[db].[dbo].[TB_TEST] as ts
on local.L_ID = ts.L_ID
LEFT JOIN [server].[db].[dbo].[TB_EXE] as ex
on ts.A_ID = ex.T_ID
现在我试图这样做:
SELECT DISTINCT
local.L_ID
FROM dbo.local_table AS local
INNER JOIN (
SELECT *
FROM OPENQUERY(SERVER,'SELECT L_ID FROM TB_TEST'
) ts
on local.L_ID = ts.L_ID
left join OPENQUERY(SERVER,'SELECT T_ID FROM TB_EXE') ex
on ts.A_ID = ex.T_ID
你能帮助我以正确的方式做到这一点,以便查询运行得更快吗?
答案 0 :(得分:1)
这种查询(带有链接服务器)可能很慢,因为当前实例与另一个服务器连接不良,或者其中一个服务器上使用的是旧版本的SQL Server。有关此article的更多信息。
我建议你使用临时表:
SELECT *
INTO #ts
FROM OPENQUERY(SERVER,'SELECT L_ID FROM TB_TEST;')
SELECT *
INTO #ex
FROM OPENQUERY(SERVER,'SELECT T_ID FROM TB_EXE;')
SELECT DISTINCT
l.L_ID
FROM dbo.local_table AS l
INNER JOIN #ts
on l.L_ID = ts.L_ID
LEFT JOIN #ex
on ts.A_ID = ex.T_ID
DROP TABLE #ts
DROP TABLE #ex
关于您的查询。
你使用几乎正确的语法。试试吧:
SELECT DISTINCT
local.L_ID
FROM dbo.local_table AS local
INNER JOIN (
SELECT *
FROM OPENQUERY(SERVER,'SELECT L_ID FROM TB_TEST;')
) ts
on local.L_ID = ts.L_ID
left join (
SELECT *
FROM OPENQUERY(SERVER,'SELECT T_ID FROM TB_EXE;')
) ex
on ts.A_ID = ex.T_ID
或者:
SELECT DISTINCT
local.L_ID
FROM dbo.local_table AS local
INNER JOIN OPENQUERY(SERVER,'SELECT L_ID FROM TB_TEST;') ts
on local.L_ID = ts.L_ID
left join OPENQUERY(SERVER,'SELECT T_ID FROM TB_EXE;') ex
on ts.A_ID = ex.T_ID
另请注意,您正在使用LEFT JOIN与第三个表,并且根本不使用它。