2012-06-14 28 views
3

我需要sql數據庫端的幫助。和我有加入sql表的CASE

表1:ENTITY_TYPE

entity_type_id entity_name 
    1   Task 
    2   Page 
    3   Project 
    4   Message 
    5   User 

和表2:MESSAGE,它包含消息從每個實體值等

message_id entity_type owner_tableid message 
    1   1    12  A message on task level 
    2   3    14  A message on project level 

,我想根據每個實體類型選擇這些消息和來自其所有者表的詳細信息,使用'owner_tableid'即查詢,例如....

select * from MESSAGE JOIN 
case entity_type when 1 then taskTable 
when 2 then pageTable 
when 3 then projectTable 
when 4 then MessageTable 
when 5 then UserTable 

哪種方法是解決單個過程中的問題的最佳方法。任何想法 ??我現在用IF子句爲每個實體...

回答

4

您不能參數化參與查詢的(因此您不能將表名稱放入變量中,並且期望也可以使用)。

一種方式來做到這一點是因爲左鏈聯接:

select 
    * /* TODO - Pick columns */ 
from 
    MESSAGE m 
     left join 
    taskTable tt 
     on 
     m.entity_type = 1 and 
     m.owner_entity_id = tt.id 
     left join 
    pageTable pt 
     on 
     m.entity_type = 2 and 
     m.owner_entity_id = pt.id 
     left join 
    projectTable prt 
     on 
     m.entity_type = 3 and 
     m.owner_entity_id = prt.id 
     left join 
    MessageTable mt 
     on 
     m.entity_type = 4 and 
     m.owner_entity_id = mt.id 
     left join 
    UserTable ut 
     on 
     m.entity_type = 5 and 
     m.owner_entity_id = ut.id 

如果你想從這些表中的值在一列中出現在結果中,使用跨所有值的COALESCE,例如

COALESCE(tt.Value,pt.Value,prt.Value,mt.Value,ut.Value) as Value 
+0

我是說發現這個佈局難以閱讀的唯一一個?這就像嘗試閱讀Jenga拼圖上的代碼。 +1,因爲解決方案是一個可行的答案;只是很難閱讀。 – Thomas

+0

我喜歡這個解決方案。但是,如果有很多實體類型,我們希望創建一個非常大的查詢。如果在查詢中使用view,pivot ...等任何簡單的方法。 –

0

如果你需要在一個查詢返回幾個entity_types細節,除了UNION可能幫助:

SELECT interesting_columns FROM Message 
JOIN pageTable ON (joinPredicate) 
WHERE entity_type = 1 

UNION ALL 

SELECT interesting_columns FROM Message 
JOIN pageTable ON (joinPredicate) 
WHERE entity_type = 2 

-- ... 

但是如果你只需要一定的ENTITY_TYPE比的細節你與IF原來的解決方案會好得多。

0
Select ... 
From Message 
    Join (
      Select 1 As entity_type, id 
      From taskTable 
      Union All 
      Select 2, id 
      From pageTable 
      Union All 
      Select 3, id 
      From projectTable 
      Union All 
      Select 4, id 
      From messageTable 
      Union All 
      Select 5, id 
      From userTable 
      ) As Z 
     On Z.entity_type = Message.entity_type 
      And Z.id = Message.owner_tableid 
1

使用UNION子句與您的個人ENTITY_TYPE

SELECT * FROM Message 
JOIN pageTable ON .... 
WHERE entity_type = 1 

UNION ALL 
.......... 
entity_type = 2 

UNION ALL 
.......... 
entity_type = 3