首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > oracle >

这种sql语句该怎么查询

2013-08-13 
这种sql语句该如何查询有一张表数据table1idtableNamerefId-----------------------1table2k12table3h1tab

这种sql语句该如何查询


有一张表数据

table1

id   tableName  refId       
-----------------------            
1      table2      k1
2      table3      h1


table2

 t2id    value
-------------
 k1     kkk
 k2     hhh


table3

t3id    value
-------------
h1    呵呵
h2    哈哈


注:table1  的tableName 是其他表名  refId是关联的id字段...

如何使用sql语句  
使table1 动态查询所关联的value(根据tableName字段和refID来查到对应的value)



期望结果:

table1

id   tableName  refId    value
-------------------------------            
1      table2      k1    kkk
2      table3      h1    呵呵


SQL
[解决办法]
select table1.id,
       table1.tableName,
       table1.refId,
       (select table2.value
            from table2
           where table2.t2id = table1.refId
         union
        select table3.value
            from table3
           where table3.t3id = table1.refId   
        ) as value
from table1



这样应该可以,机子没有装数据库过,有问题这个SQL你改改应该就可以了
[解决办法]
我的思路是这样的,你要做的就是找到表1中字段refId对应的码表。
你可以不用动态语句,直接的把表2和表3通过union  all 连接起来

热点排行