简体   繁体   中英

Join queries from two different databases on the same server?

I have two DB's on the same server. I have two simple select queries for each DB which work correctly. But, when combined into a join, they fail. I want to fix this.

Pseudocode -

select *
from (select columns from DB1) as D1
inner join 
select *
from (select columns from DB2 where some valid condition) as D2
on D1.column1 = D2.column1

Error -

Incorrect syntax near the keyword 'SELECT'. (ie second "outer" select)
Incorrect syntax near the keyword 'on'.

Jeez - all i had to do was this -

select *
from (select columns from DB1) as D1
inner join 
--select *
--from 
(select columns from DB2 where some valid condition) as D2
on D1.column1 = D2.column1

See the commented lines. Remove them and it should work.

Note, to include columns selected from D2, put the D2 columns in the uppermost select statement.

select col1b, col2c
from (select col1a, col1b from DB1) as D1
inner join 
--select *
--from 
(select col2a, col2b, col2c from DB2 where some valid condition) as D2
on D1.col1a = D2.col2a

This will display col1b and col2c.

select *
from DataBaseName.ShemaName.TableName1 D1 inner join  DataBaseName.ShemaName.TableName2 D2
on D1.column1 = D2.column1
WHERE Somecondition

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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