用于加入sql表的CASE

时间:2012-06-14 06:27:51

标签: sql sql-server sql-server-2008 sql-server-2005

我需要在sql数据库端提供帮助。我有

表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 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

将Union Clause与您的个体entity_type

一起使用
SELECT * FROM Message
JOIN pageTable ON ....
WHERE entity_type = 1

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

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

答案 2 :(得分: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会更好。

答案 3 :(得分: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
相关问题