2012-04-26 41 views
1

我有8個主表,每個表有大約60萬條記錄。加入更多父表

讓我們假設表名是

type_11_14 
type_12_15 
type_13_16 
type_4_5 
type_6 
type_7 
type_8 
type_10 

每個表都有代碼列。 代碼主鍵。 我無法合併所有這些表並製作一張表。

在上述表中列出type_11_14已經鍵入11和14記錄 和type_7已鍵入7記錄

我有其他表all_types_count。它計算了上述類型的信息。 對於類型和代碼給定的名單(我們給予最大碼是50),我需要得到它的名稱,類型,代碼和計數

我已經寫了與UNION下面的查詢。查詢運行正常。但是,如果我運行解釋計劃,我得到

錯誤 未能啓用約束。一行或多行包含違反非空,唯一或外鍵約束的值。

再次在下面的查詢我查詢all_types_count表8次。而不是我想從all_types_count獲得所有記錄,然後離開加入主表以獲得所需的結果。

不知道什麼可能是最好的SQL查詢解決方案。有人能爲我提供最好的方法嗎?

SELECT type,code,total_count,type_11_14.name 
FROM all_types_count,type_11_14 
WHERE all_types_count.type in (11,14) 
AND all_types_count.code=type_11_14.code 
AND all_types_count.code in (3456,6789) 

UNION ALL 

SELECT type,code,total_count,type_12_15.name 
FROM all_types_count,type_12_15 
WHERE all_types_count.type in (12,15) 
AND all_types_count.code=type_12_15.code 
AND all_types_count.code in (2345,9087,234) 

UNION ALL 

SELECT type,code,total_count,type_13_16.name 
FROM all_types_count,type_13_16 
WHERE all_types_count.type in (13,16) 
AND all_types_count.code=type_13_16.code 
AND all_types_count.code in (98,24) 

UNION ALL 

SELECT type,code,total_count,type_4_5.name 
FROM all_types_count,type_4_5 
WHERE all_types_count.type in (4,5) 
AND all_types_count.code=type_4_5.code 
AND all_types_count.code in (765,9087,3456) 

UNION ALL 

SELECT type,code,total_count,type_6.name 
FROM all_types_count,type_6 
WHERE all_types_count.type=6 
AND all_types_count.code=type_6.code 
AND all_types_count.code in (5563,323,434,3442) 

UNION ALL 

SELECT type,code,total_count,type_7.name 
FROM all_types_count,type_7 
WHERE all_types_count.type=7 
AND all_types_count.code=type_7.code 
AND all_types_count.code in (7887,313,23,32,21) 

UNION ALL 

SELECT type,code,total_count,type_8.name 
FROM all_types_count,type_8 
WHERE all_types_count.type=8 
AND all_types_count.code=type_8.code 
AND all_types_count.code in (9988,1221) 

UNION ALL 

SELECT type,code,total_count,type_10.name 
FROM all_types_count,type_10 
WHERE all_types_count.type=10 
AND all_types_count.code=type_10.code 
AND all_types_count.code in (7787,23213) 

謝謝

基蘭

回答

1

如果寫成您的查詢應該是更有效的:

SELECT type,code,total_count,type_11_14.name 
FROM all_types_count 
left outer join type_11_14 
    on all_types_count.type in (11,14) 
    and all_types_count.code=type_11_14.code 
    and all_types_count.code in (3456,6789) 
left outer join type_12_15 
    on all_types_count.type in (12,15) 
    and all_types_count.code=type_12_15.code 
    and all_types_count.code in (2345,9087,234) 
left outer join . . . 

如果你不熟悉的加入/左外連接/右外連接/交叉連接語法,那麼你應該學習它。

在您的原始查詢中,優化器很可能會爲每個子查詢讀取一次all_types_count表。使用連接時,應該只讀一次,並根據需要加入其他表。

+0

謝謝你的查詢Gordon,This help me – Bujji 2012-04-30 17:09:09