Oracle获取外键
我想获取模式中的所有外键,如下所示。 假设我有表
users(id, username, pass, address_id)
和
addresses(id, text)
我已经在 users-address_id 上定义了一个 FK 到 id 列地址。 我应该如何编写一个查询来返回 FK 列,例如: 用户、address_id、地址、id ?
谢谢!
SELECT *
FROM all_cons_columns a
JOIN all_constraints c ON a.owner = c.owner
AND a.constraint_name = c.constraint_name
JOIN all_constraints c_pk ON c.r_owner = c_pk.owner
AND c.r_constraint_name = c_pk.constraint_name
WHERE C.R_OWNER = 'TRWBI'
I'd like to get all foreign keys in a schema, like this.
Let's say I have tables
users(id, username, pass, address_id)
and
addresses(id, text)
I have defined a FK on users-address_id to the id column in addresses.
How should I write a query that would return me the FK columns like :
users, address_id, addresses, id ?
Thanks!
SELECT *
FROM all_cons_columns a
JOIN all_constraints c ON a.owner = c.owner
AND a.constraint_name = c.constraint_name
JOIN all_constraints c_pk ON c.r_owner = c_pk.owner
AND c.r_constraint_name = c_pk.constraint_name
WHERE C.R_OWNER = 'TRWBI'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
找到了!
这就是我一直在寻找的,感谢大家的帮助。
found it!
this is what i was looking for, thanks everybody for helping.
使用 @maephisto 解决方案会出现一个小错误:
如果
源表主键是复合键
,则运行查询将导致重复不必要的记录
。考虑 T1 和 T2 表:
主表 T1:
明细表 T2:
@maephisto 查询的结果将是:
为了解决这个问题,下面的查询将服务:
Using @maephisto solution will case a little bug:
If the
source tables primary key is a composite key
then running the query will resultduplicate unnecessary records
.Consider T1 and T2 tables:
Master table T1:
Detail table T2:
The result of the @maephisto query will be:
To over come the problem the query bellow will serve:
它们列在系统视图
ALL_CONSTRAINTS
http://download.oracle.com/docs/cd/B19306_01/server.102/b14237/statviews_1037.htm#i1576022
编辑
涉及的列约束列于
ALL_CONS_COLUMNS
http://download.oracle.com/docs/cd/B19306_01/server.102/b14237/statviews_1035.htm#i1575870
They are listed in the system view
ALL_CONSTRAINTS
http://download.oracle.com/docs/cd/B19306_01/server.102/b14237/statviews_1037.htm#i1576022
Edit
The columns involved in the constraints are listed in
ALL_CONS_COLUMNS
http://download.oracle.com/docs/cd/B19306_01/server.102/b14237/statviews_1035.htm#i1575870