2016-02-08 24 views
1

我試圖創建一個命令將客戶成員的細節從一個數據庫具有相同的結構複製到另一個選擇。爲了解決問題,我已經將它縮減爲最基本的要素,因此要複製的四個項目是到期日期,訂閱ID,客戶端ID和項目ID(它是構成訂閱的服務)。 客戶在兩個基地都有一個共同的GUID。訂閱ID是一個獨特的long int,在兩個基數中應該是相同的,並且到期日僅僅是一個日期。到目前爲止,這麼容易。棘手的部分是每個數據庫中的item_id不一定相同。我需要用where語句映射到另一個,我知道該怎麼做。從多個表中沒有笛卡爾積

我的問題是,我需要從目標數據庫中自己的項目表(item_0),以獲得並插入正確的選擇ITEM_ID,我這樣做時,我得到成千上萬的重複行返回。我假設我需要使用連接來避免這種情況,但是因爲我沒有任何意義可以加入item_0,所以我無法獲得任何結果。

insert into DestDB..subscription (expiry_date,id,client_id,item_id) 
select 
    sub_1.expiry_date, 
    sub_1.id, 
    cli_0.id as client_id, 
    item_0.id as item_id, 
from 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] 
where sub_1.id not in (select id from DestDB..subscription) 
and item_0.id = 
    (select id from DestDB..collectiondetails 
      where service_ID = 
       (select id from DestDB..service s_0 where s_0.code = 
       (select code from SourceDB..service s_1 where s_1.id = 
        (select service_ID from Source..collectiondetails item_1   where item_1.id = sub_1.item_id))) 
      and collection_ID = 
       (select id from DestDB..collection col_0 
        where col_0.code = 
        (select code from SourceDB..collection col_1 where col_1.id = 
         (select collection_ID from SourceDB..collectiondetails item_1 where item_1.id = sub_1.collection_ID))) 

    )   
+0

表DestDB..item和DestDB..client是如何連接的,有沒有FK? –

+0

他們之間沒有直接的聯繫。兩者都通過subscription.client_id連接到DestDB.subscription並且subscription.item_id – pickarooney

+1

如果您「沒有意義加入item_0」,您希望如何爲給定訂閱選擇正確的項目。一定有東西。否則,您也可以選擇一個隨機項目。 –

回答

0

恐怕更新後的問題更加令人困惑。難道這SelectWhere子句保證只返回一個記錄,或者它應該是in,而不是=

如果沒有規則,從再選配頂部應該做的一樣好名單識別特定DestDB..item。它仍然看起來,item_0可以完全省略:

insert into DestDB..subscription (expiry_date,id,client_id,item_id) 
select 
    sub_1.expiry_date, 
    sub_1.id, 
    cli_0.id as client_id, 
    (select Top 1 id from DestDB..collectiondetails --<- Limit to top 1 only 
      where service_ID = 
       (select id from DestDB..service s_0 where s_0.code = 
       (select code from SourceDB..service s_1 where s_1.id = 
        (select service_ID from SourceDB..collectiondetails item_1 where item_1.id = sub_1.item_id))) 
      and collection_ID = 
       (select id from DestDB..collection col_0 
        where col_0.code = 
        (select code from SourceDB..collection col_1 where col_1.id = 
         (select collection_ID from SourceDB..collectiondetails item_1 where item_1.id = sub_1.collection_ID))) 
    ) as item_id, 
from SourceDB..subscription sub_1, 
    DestDB..client cli_0 
inner join SourceDB..client cli_1 
    on cli_1.[guid] = cli_0.[guid] 
where sub_1.id not in (select id from DestDB..subscription) 

請注意:如果DestDB..item是空的問題例如語句將不插入任何東西,但這個答案一個 - 將與item_id設置爲NULL

我個人會嘗試拆分這個任務分成兩個單獨的語句在一個事務中:

  1. 插入到目標表與NULL ITEM_ID。
  2. 使用新的item_id更新目標表,其中item_id爲NULL。
  3. (可選)在找不到合適的item_id時刪除不需要的記錄。
+0

見上文。對不起原來問題的模糊性,我試圖通過張貼太多的信息來限制混淆,但我意識到我不清楚。 – pickarooney