SQL 连接多个表 [英] SQL joining multiple tables
本文介绍了SQL 连接多个表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用 Microsoft SQL 2000,我想将多个表(A、B、C 和 D)连接在一起.我知道表 A 始终存在.但是,我只知道至少存在一种表格形式(B、C、D).
Using Microsoft SQL 2000, I will like to join multiples tables (A, B, C, and D) together. I know table A always exists. However, I only know at least one of the table form (B, C, D) exists.
有什么办法可以做这样的事情来完成我想要做的事情吗?
Is there any way I could do something like this to accomplish what I am trying to do?
Select * form table a
If table b exists left Join table b on a.id = b.id
If table c exists left Join table c on a.id = c.id
If table d exists left Join table d on a.id = d.id
推荐答案
你必须检查数据字典视图并使用动态 SQL
You'll have to check the data dictionary views for that and use dynamic SQL
declare @myquery varchar(1000)
set @myquery = 'Select * from a '
if exists (select * from sysobjects where xtype='U' and name = 'b')
begin
set @myquery = @myquery + 'inner join b on b.id = a.id '
end
if exists (select * from sysobjects where xtype='U' and name = 'c')
begin
set @myquery = @myquery + 'inner join c on c.id = a.id '
end
if exists (select * from sysobjects where xtype='U' and name = 'd')
begin
set @myquery = @myquery + 'inner join d on d.id = a.id '
end
exec( @myquery)
我使用过 sysobjects
,但是我们鼓励您使用 信息架构视图 代替
I've used sysobjects
, however you are encouraged to use Information Schema Views instead
而且,对动态 SQL 的重大免责声明
优势
- 它提供了灵活性和可扩展性
- 它可以减少编写的代码行数
缺点
- 它可能变得非常复杂且难以阅读.想想嵌入在引号中的引号,以及其他类似的东西.
- 它会对代码稳定性产生不利影响.一些动态 SQL 错误直到运行时才会知道.(例如,您引用了一个不存在的表)
- 动态 SQL 代码比等效的静态 SQL 更难测试.也可能无法测试您的动态 SQL 将遇到的所有可能情况,从而引入固有风险.
- 对代码库中的动态 SQL 进行有效的影响分析会更加困难.
- SQL 注入和误用 - 动态 SQL 更容易被误用,并且总是不如静态 SQL 安全
- 动态 SQL 中的查询代码不受查询计划的约束,因此可能会错过此类优化.因此,它可能比等效的静态 SQL 慢
- 由于 SQL 查询直到运行时才知道,因此可能更难对 SQL 动态代码进行性能调优(例如,确定表上可能需要的索引)
这篇关于SQL 连接多个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文