2011-03-27 38 views
0

我已經在這裏做了一些搜索,但不能拿出答案,所以我想問這是否可能...這是否可以使用Mysql條件連接?

我想根據數據庫中的字段值創建條件連接。因此,例如,如果值爲1,那麼如果值爲2,則加入一個表,然後加入不同的表。

這裏是我有工作的一些樣本數據:

Templates Table 

template_id  name    type 
    1   Email Template  1 
    2   Page Template  2 


Email Templates Table 

template_id  email_subject  email_body 
    1    test    test 


Page Templates Table 

template_id  page_title  page_desc 
    2    test page  testing 

所以模板表包含了所有的通用模板信息和其他表contins特定的模板類型信息。

是否有可能創建條件mysql連接,所以如果模板表中的類型爲1,那麼從電子郵件表中,如果類型爲2,那麼從頁表中連接?

如果沒有人能提出更好的模板數據庫設計?

任何幫助,將不勝感激。

感謝

回答

1
select t.*, 
     coalesce(e.email_subject, p.page_title) title_or_subject, 
     coalesce(e.email_body, p.page_desc) body_or_desc 
from Templates t 
left join EmailTemplates e on t.type=1 and e.template_id=t.template_id 
left join PageTemplates p on t.type=2 and p.template_id=t.template_id 

向左雙連接將顯示,即使它不能從任一臺(根據類型)匹配的所有模板。否則,如果它必須存在於表示該類型的模板表中,則

select t.*, 
     coalesce(e.email_subject, p.page_title) title_or_subject, 
     coalesce(e.email_body, p.page_desc) body_or_desc 
from Templates t 
left join EmailTemplates e on t.type=1 and e.template_id=t.template_id 
left join PageTemplates p on t.type=2 and p.template_id=t.template_id 
where ((t.type = 1 and e.template_id is not null) 
    or (t.type = 2 and p.template_id is not null)) 
+0

您可以始終進行FULL OUTTER JOIN。儘管加入3張桌子時,您最終會得到三張桌子的笛卡爾產品,這可能最終會變得非常龐大! – Suroot 2011-03-27 03:00:06

+0

感謝您的答案,我剛剛測試過,效果很好。你會建議我堅持這個查詢和數據庫設計還是有更好/更有效的方法來做到這一點? – 2011-03-27 03:15:04

相關問題