根据其他列值查询表

时间:2010-05-27 13:33:08

标签: sql

有没有办法根据查询中列的值查询不同的数据库?

比如说您有以下列:

  • ID
  • PART_ID
  • attr_id
  • attr_value_ext
  • attr_value_int

然后运行查询,如果attr_id为'1',则返回attr_value_int列,但如果attr_id大于'1',则根据attr_value_ext从另一个表中加入数据。

5 个答案:

答案 0 :(得分:4)

这样的事情?

select case when a.id = 1 then a.attr_value_int
            when a.id > 1 then b.some_other_col
            else null end as whatever
from first_table a
     left outer join other_table b
     on ( a.attr_val_ext = b.id )
/

答案 1 :(得分:2)

您可以在on子句中使用条件,例如:

select    case when attr_id = 1 then attr_value_int
               when attr_id = 2 then t1.value_int
               when attr_id = 3 then t2.value_int
          end
from      YourTable yt
left join Table1 t1 
on        t1.attr_id = 2 and yt.part_id = t1.part_id
left join Table2 t2 
on        t1.attr_id = 3 and yt.part_id = t2.part_id

如果表的数量相对较小并且事先已知,这将最有效。否则,您将不得不求助于动态SQL,或者从客户端构建后续查询。

答案 2 :(得分:1)

很难根据该描述给出确切答案......

你应该可以用UNION

来做到这一点
select stuff from one table where attr_id = 1
UNION
select stuff from another table where attr_id > 1

答案 3 :(得分:0)

SQL规范中没有任何内容,但通常有特定于DB的函数可以为您执行此操作。例如,oracle上的解码对你有用。

答案 4 :(得分:0)

SELECT ID,PART_ID,ATTR_ID,CASE
  WHEN attr_id =1 THEN attr_value_int  
  WHEN attr_id >1 THEN <SELECT QUERY>
  END <My Column>
from TABLE;

也许这会起作用