2011-03-27 15 views
0

私はここで少しの検索をしましたが、答えが出ないので、これが可能かどうか尋ねたいと思っていました...このMysql条件付き結合は可能ですか?

データベースのフィールドの値に基づいて条件付き結合を作成したいとします。たとえば、値が1の場合は、値が2の場合は1つの表を結合し、別の表を結合します。ここで

は、私が仕事をしなければならないいくつかのサンプルデータです:

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つのテーブルを結合すると、3つのテーブルすべてのデカルト積で終わることになりますが、最終的には巨大になることがあります。 – Suroot

+0

私はちょうどテストした答えをありがとう、それはうまく動作します。私はこのクエリとデータベース設計に固執することを提案するか、これを行うためのより効率的な方法がありますか? –

関連する問題