这种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 连接起来