sql server - Select from multiple tables without cartesian product -
i'm trying create command copy details of client memberships 1 database identical structure. i've pared down bare essentials purposes of question 4 items copy expiry date, subscription id, client id , item id (which service comprises subscription). clients have common guid in both bases. subscription id unique long int should same in both bases , expiry date date. far, easy. tricky part item_id not same in each database. need map 1 the other statement, know how do.
my problem need select destination database's own item table (item_0) in order , insert correct item_id , when thousands of duplicate rows returned. assume need use join avoid have nothing meaningful join item_0 can't results.
insert destdb..subscription (expiry_date,id,client_id,item_id) select sub_1.expiry_date, sub_1.id, cli_0.id client_id, item_0.id item_id, sourcedb..subscription sub_1, destdb..item item_0, destdb..client cli_0 inner join sourcedb..client cli_1 on cli_1.[guid] = cli_0.[guid] sub_1.id not in (select id destdb..subscription) , item_0.id = (select id destdb..collectiondetails service_id = (select id destdb..service s_0 s_0.code = (select code sourcedb..service s_1 s_1.id = (select service_id source..collectiondetails item_1 item_1.id = sub_1.item_id))) , collection_id = (select id destdb..collection col_0 col_0.code = (select code sourcedb..collection col_1 col_1.id = (select collection_id sourcedb..collectiondetails item_1 item_1.id = sub_1.collection_id))) )
i afraid updated question more confusing. select
in where
clause guaranteed return 1 record or should in
instead of =
?
if there no rule identify particular destdb..item
list of matching top 1 should well. still seem item_0
can omitted altogether:
insert destdb..subscription (expiry_date,id,client_id,item_id) select sub_1.expiry_date, sub_1.id, cli_0.id client_id, (select top 1 id destdb..collectiondetails --<- limit top 1 service_id = (select id destdb..service s_0 s_0.code = (select code sourcedb..service s_1 s_1.id = (select service_id sourcedb..collectiondetails item_1 item_1.id = sub_1.item_id))) , collection_id = (select id destdb..collection col_0 col_0.code = (select code sourcedb..collection col_1 col_1.id = (select collection_id sourcedb..collectiondetails item_1 item_1.id = sub_1.collection_id))) ) item_id, sourcedb..subscription sub_1, destdb..client cli_0 inner join sourcedb..client cli_1 on cli_1.[guid] = cli_0.[guid] sub_1.id not in (select id destdb..subscription)
please note: if destdb..item
empty question example statement not insert anything, answer 1 - item_id
set null
.
i try splitting task 2 separate statements in 1 transaction:
- insert target table null item_id.
- update target table new item_id item_id null.
- (optional) delete unwanted records appropriate item_id not found.
Comments
Post a Comment