2016-10-25 93 views
-2

我使用python訪問SQL服務器的數據庫。該數據庫有大約200個表,並且它包含表之間的外鍵。使用SQL服務器中的外鍵自動加入表,pyodbc

我想使用數據庫中的外鍵自動連接表,因爲手動操作非常繁瑣。

如何使用給定的外鍵創建所有表的所有最大可能連接的熊貓數據框?

隨着pyodbc,我能順利拿到每一個具體的表格製作這一行代碼連接後:

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

它不清楚是什麼你問 – tuergeist

+0

@tuergeist該數據庫包含的表和它們之間的外鍵,這是所有的人需要計算在它們之間具有外鍵每兩個表之間的連接。只要我能夠創建幾張大桌子,我就想反覆加入所有桌子。 – User9123

+0

目前還不清楚,這是一個python還是一個數據庫問題 – tuergeist

回答

0

這不是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;