条件选择的SQL语法

条件选择的SQL语法,sql,sql-server,Sql,Sql Server,我试图从三个表中选择数据。我的逻辑应该是这样的: 基本上,从由表a中的列确定的两个表中选择一个 选择一个.orderid, 如果(a.ordertable=b),则b.order\u信息 其他的 c、 订单信息 哪里 a、 订单id=b.订单id或a.订单id=c.订单id 有指针吗?使用CASE SELECT a.orderid, CASE WHEN a.ordertable = b.? THEN b.order_info ELSE c.order_i

我试图从三个表中选择数据。我的逻辑应该是这样的:

基本上,从由表a中的列确定的两个表中选择一个

选择一个.orderid,
如果(a.ordertable=b),则b.order\u信息
其他的
c、 订单信息
哪里
a、 订单id=b.订单id或a.订单id=c.订单id
有指针吗?

使用
CASE

SELECT a.orderid,
    CASE
        WHEN a.ordertable = b.? THEN b.order_info
        ELSE c.order_info
    END
FROM sparkles
WHERE a.order_id = b.order_id OR a.order_id = c.order_id
使用
CASE

SELECT a.orderid,
    CASE
        WHEN a.ordertable = b.? THEN b.order_info
        ELSE c.order_info
    END
FROM sparkles
WHERE a.order_id = b.order_id OR a.order_id = c.order_id

我想到的是两个子查询,它们联合在一起以获得每个表的结果:

select *
from ((select b.order_info
       from b join
            a
            on a.order_id = b.order_id and
               a.ordertable = 'b'
      )
      union all
      (select c.order_info
       from c join
            a
            on a.order_id = c.order_id and
               c.ordertable = 'c'
     )
    ) t

我想到的是两个子查询,它们联合在一起以获得每个表的结果:

select *
from ((select b.order_info
       from b join
            a
            on a.order_id = b.order_id and
               a.ordertable = 'b'
      )
      union all
      (select c.order_info
       from c join
            a
            on a.order_id = c.order_id and
               c.ordertable = 'c'
     )
    ) t

假设表b或c中的行可能存在,也可能不存在,我认为您需要:

select  a.orderid,
        case 
            when a.ordertable = 'b' then b.order_info
            else c.order_info
        end as order_info
from    a
left 
join    b
        on a.orderid = b.orderid
left 
join    c
        on a.orderid = c.orderid

假设表b或c中的行可能存在,也可能不存在,我认为您需要:

select  a.orderid,
        case 
            when a.ordertable = 'b' then b.order_info
            else c.order_info
        end as order_info
from    a
left 
join    b
        on a.orderid = b.orderid
left 
join    c
        on a.orderid = c.orderid

此查询没有“from”子句。@GordonLinoff也没有。但我会更新。谢谢:)此查询没有“from”子句。@GordonLinoff也没有。但我会更新。谢谢:)