2015-06-24 28 views
0

我只想使用(My)SQL語句在MySQL中填充關係表。問題是,爲什麼我現在要做的是,我必須用條件填充依賴於其他表格的數據。我從來沒有做過很多有關條件編程和SQL內循環,我現在試過的每一個部分,使它以某種方式工作失敗悲慘。我可能想稍後將結果存儲爲存儲過程,但現在工作語句不會令人滿意。用MySQL中的其他5個表填充數據表

表設置:

我有5代表具有數據和我需要填寫第六一個與關係的數據。表結構是這樣的:

table setup

現在我要填寫僅使用SQL(MySQL的)以下規則CategoryProducts(僞碼)

foreach category-id: 
    if allTags is true then 
    fetch each product-id that has all tags that the category has 
    else 
    fetch each product-id that has at least one tag that the category has 
    fi 

    insert each product-id matching into CategoryProducts 
end foreach 

說實話,我不知道如何做到這一點,只使用普通的SQL。我通常會通過代碼實現這一點,但這次我不能這樣做。我想用它作爲我們某個外部服務器的安裝腳本的一部分,但在安裝例程的這一部分中,我只能執行SQL語句。

編輯:刪除表格設置圖片中的醜陋的鼠標光標。

+1

這個問題讓我有點糊塗了。如果您發佈表格定義,它可能會有所幫助。 –

回答

1

我想你可以用「簡單」 INSERT..SELECT做到這一點:

insert into CategoryProducts(cID, pID) 
select 
    -- The field list in `select` should match the list in the `insert into` clause. 
    x.cID, 
    x.pID 
from 
    -- Inner select returns all possible combinations, yet unfiltered by the 
    -- conditions you specified, and returns the number of tags 
    -- for each product, each catagory, and the number of tags they share. 
    -- If SharedTagCount = cTagCount, it means that the product has all the tags 
    -- of the category (not necessarily the other way around). 
    (select 
    p.ID as pID, 
    c.ID as cID, 
    c.allTags, 
    (select count(*) from ProductTags pt where pt.pID = p.ID) as pTagCount, 
    (select count(*) from CategoryTags ct where ct.cID = c.ID) as cTagCount, 
    (select 
     count(*) 
    from 
     ProductTags pt 
     inner join CategoryTags ct on ct.tCode = pt.tCode 
    where 
     pt.pID = p.ID and 
     ct.cID = c.ID) as SharedTagCount 
    from 
    Product p 
    cross join Categories c) x 
where 
    -- Outer select filters. 
    -- if SharedTagCount = cTagCount, it means that the product has all 
    -- the tags of the category. 
    (x.AllTags and 
    x.cTagCount = x.SharedTagCount) or 
    -- if SharedTagCount > 0, it means the product has at least one tag of the category. 
    ((not x.AllTags) and 
    x.SharedTagCount > 0)  
+0

哦,我不知道我可以在insert語句中以這種方式堆棧select。我現在要檢查一下。 – Ello

+0

所以,我試圖在開發上。它似乎工作,但在第一個10.000條目後,它失去了與數據庫的連接。我需要弄清楚這是從哪裏來的。我現在感謝你的回答,但我需要首先驗證結果。 :) – Ello

+0

好吧,它的方式來執行。我仍然在想出如何減少執行時間。 15分鐘後仍未完成。我瀏覽了鍵/索引,但沒有什麼我可以在表格基礎上改變,也許我可以改變語句中的連接以獲得相同的效果。我會寫回 - – Ello

相關問題