【问题标题】:Automatically joining the tables using the foreign keys in SQL server, pyodbc使用 SQL Server 中的外键自动连接表,pyodbc
【发布时间】:2016-10-25 06:44:23
【问题描述】:

我使用 python 访问 SQL 服务器的数据库。该数据库有大约 200 个表,并且包含表之间的外键。

我想使用数据库中的外键自动连接表,因为手动操作非常繁琐。

如何使用给定的外键创建表的所有最大可能连接的 pandas 数据框?

使用pyodbc,用这行代码创建连接后,我可以成功获取每个特定的表:

cnxn = pyodbc.connect("...")

【问题讨论】:

  • 不清楚你的要求是什么
  • @tuergeist 数据库包含表和它们之间的外键,这就是计算每两个具有外键的表之间的连接所需的全部内容。我想尽可能地重复加入所有表以创建几个大表。
  • 目前还不清楚,这是python还是数据库问题

标签: python sql-server database foreign-keys pyodbc


【解决方案1】:

这不是 SQL 的标准特性。您将不得不查询系统模式表中的关系,然后自己构建查询,可能使用左连接。 我目前正在尝试类似的东西,这是我用来从 SQL Server 获取关系的 SQL。

with fKC as
(
    select
            sfkc.constraint_object_id
            ,(select name from sys.objects as o where o.object_id=sfkc.constraint_object_id) as constraint_object_name
            ,sfkc.parent_object_id
            ,(select name from sys.objects as o where o.object_id=sfkc.parent_object_id) as parent_object_name
            ,sfkc.parent_column_id
            ,(select name from sys.columns as c where ((c.object_id=sfkc.parent_object_id)and(c.column_id=sfkc.parent_column_id))) as parent_column_name
            ,sfkc.referenced_object_id
            ,(select name from sys.objects as o where o.object_id=sfkc.referenced_object_id) as referenced_object_name
            ,sfkc.referenced_column_id
            ,(select name from sys.columns as c where ((c.object_id=sfkc.referenced_object_id)and(c.column_id=sfkc.referenced_column_id))) as referenced_column_name
    from sys.foreign_key_columns as sfkc
    where (sfkc.parent_object_id!=sfkc.referenced_object_id)
)

select *
from fKC
order by fKC.parent_object_name, fKC.referenced_object_name;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-28
    • 2014-09-11
    • 1970-01-01
    • 2013-03-22
    • 1970-01-01
    相关资源
    最近更新 更多