查找特定记录可用的数据库

时间:2013-12-11 07:14:33

标签: sql sql-server database oracle

考虑有三个数据库说D1, D2, D3。每个数据库中有两个表T1, T2

T1有两列C1, C2。表格T2有三列C3, C4, C5

现在我们有六张桌子。每个数据库中的记录都不同。

数据库结构:

D1:
------
T1  T2


D2:
------
T1  T2


D3:
------
T1  T2

表格结构:

T1:
------
C1  C2

T2:
----------
C3  C4  C5

我可以在每个数据库中运行相同的查询,如下所示,以获取输出并查找哪个数据库具有记录:

Select * from T1 where C1 = 'Some_value'

我的问题是,如何找到哪个数据库有我想要的记录,而不运行查询三次...... ??

注意:可以有N个数据库,每个数据库都有M个表。

3 个答案:

答案 0 :(得分:3)

您可以运行这样的查询(下面的SQL Server版本,其他dbs类似):

Select 'db1' as db, 'T1' as table from db1.dbo.T1 where 'Some_value' in (C1, C2)
union all
Select 'db1' as db, 'T2' as table from db1.dbo.T1 where 'Some_value' in (C3, C4, C5)
union all
Select 'db2' as db, 'T1' as table from db2.dbo.T1 where 'Some_value' in (C1, C2)
union all
Select 'db2' as db, 'T2' as table from db2.dbo.T1 where 'Some_value' in (C3, C4, C5)
union all
Select 'db3' as db, 'T1' as table from db3.dbo.T1 where 'Some_value' in (C1, C2)
union all
Select 'db3' as db, 'T2' as table from db3.dbo.T1 where 'Some_value' in (C3, C4, C5)

答案 1 :(得分:1)

在oracle中尝试此查询,您可以使用val作为变量:

select Tab1.* from
(Select 'D1' as DataBase,D1.T1.* from D1.T1
UNION ALL
Select 'D2' as DataBase,D2.T1.* from D2.T1
UNION ALL
Select 'D3' as DataBase,D3.T1.* from D3.T1) Tab1,
(select 'Some_value' as val from dual)Tab2
WHERE
Tab1.C1 = Tab2.val;

答案 2 :(得分:0)

是的,你需要动态的Sql。 i)首先找到你当时有多少个数据库。 然后在每个循环中通过该数据库的所有表创建另一个循环,依此类推。

顺便说一下,你首先要做的是你会有N号。数据库和M没有。每个表格。