SQL 连接多个表
我想使用 Microsoft SQL 2000 将多个表(A、B、C 和 D)连接在一起。我知道表 A 始终存在。但是,我只知道至少存在一种表形式(B、C、D)。
我有什么办法可以做这样的事情来完成我想做的事情吗?
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您必须检查数据字典视图并使用动态 SQL
,我已经使用了 sysobjects,但是我们鼓励您使用 信息架构视图 而是
动态 SQL 的重要免责声明
优点
缺点
You'll have to check the data dictionary views for that and use dynamic SQL
I've used
sysobjects
, however you are encouraged to use Information Schema Views insteadAnd, a BIG DISCLAINER ON DYNAMIC SQL
Advantages
Disadvantages
下面是查询。 * 永远不应该成为查询的一部分,因此最好提及列名称。
Below is the query. The * should never be the part of the query so better to mention the column names.
您不能以这种方式进行条件连接。
你可以做一个普通的 LEFT JOIN 。如果没有行与连接条件匹配,则这些列将为 NULL:
b.* 列可能为 NULL,或者 c.* 列可能为 NULL,或者 d.* 列可能为 NULL。
如果您需要选择第一个非 NULL 列,请使用 COALESCE:
正如评论者所说,如果表不存在,则这不起作用。我想我实际上会提倡继续创建表,以便您的模式始终符合预期。动态 SQL 维护和调试很痛苦,可以使用元数据询问静态 SQL 和模式以确保它们满足预期(即,如果表丢失,则过程或视图将无效,并且可以显式查看依赖项)
You cannot do a conditional join in that way.
You can just do an ordinary LEFT JOIN. If no row matches the join criteria, those columns will be NULL:
The b.* columns may be NULL or the c.* columns may be NULL or the d.* columns may be NULL.
If you need to pick the first non-NULL column, use COALESCE:
As commenters have said, if the tables don't exist, this doesn't work. I think I would actually advocate going ahead and creating the tables so your schemas always match expectations. Dynamic SQL is a pain to maintain and debug and static SQL and schemas can be interrogated to ensure they meet expectations using metadata (i.e. a procedure or view will not be valid if a table is missing, and dependencies can be viewed explicitly)
我猜你的意思是如果结果存在而不是表格本身。
您只会得到值不匹配的列的空值。
这样你就可以用
etc来过滤
I guess you mean if the results exist not the tables themselves.
you will just get nulls for the columns where the value did not match.
so you can filter with
etc