检查MySQL中的外键

时间:2012-10-17 03:56:46

标签: mysql foreign-keys referential-integrity

有没有办法检查MySQL中的外键完整性?例如;是否可以通过information_schema中的数据库检查每个表是否存在约束违规?

1 个答案:

答案 0 :(得分:1)

我写了一些SQL来做这件事。

首先,必须收集约束,表,列和子表信息的列表:

SELECT DISTINCT KEY_COLUMN_USAGE.CONSTRAINT_NAME, KEY_COLUMN_USAGE.TABLE_NAME, KEY_COLUMN_USAGE.COLUMN_NAME, KEY_COLUMN_USAGE.REFERENCED_TABLE_NAME, KEY_COLUMN_USAGE.REFERENCED_COLUMN_NAME 
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE 
ON TABLE_CONSTRAINTS.CONSTRAINT_NAME=KEY_COLUMN_USAGE.CONSTRAINT_NAME 
WHERE TABLE_CONSTRAINTS.CONSTRAINT_TYPE="FOREIGN KEY" AND TABLE_CONSTRAINTS.CONSTRAINT_SCHEMA=<YOUR_DATABASE>;

收集此信息后,您将使用以下SQL循环返回的数据:

SELECT PARENT_TABLE.COLUMN AS CHILD_ID, CHILD_TABLE.CHILD_REFERENCED_COLUMN AS PARENT_ID FROM <YOUR_DATABASE>.<THE_TABLE> 
LEFT JOIN <YOUR_DATABASE>.CHILD_TABLE ON PARENT_TABLE.COLUMN=CHILD_TABLE.CHILD_REFERENCED_COLUMN 
WHERE CHILD_TABLE.CHILD_REFERENCED_COLUMN IS NULL;

执行此操作的Python代码如下:

self.dbcur.execute("SELECT DISTINCT KEY_COLUMN_USAGE.CONSTRAINT_NAME, KEY_COLUMN_USAGE.TABLE_NAME, KEY_COLUMN_USAGE.COLUMN_NAME, KEY_COLUMN_USAGE.REFERENCED_TABLE_NAME, KEY_COLUMN_USAGE.REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE ON TABLE_CONSTRAINTS.CONSTRAINT_NAME=KEY_COLUMN_USAGE.CONSTRAINT_NAME WHERE TABLE_CONSTRAINTS.CONSTRAINT_TYPE=\"FOREIGN KEY\" AND TABLE_CONSTRAINTS.CONSTRAINT_SCHEMA=%s", (self.database,))
prep = self.dbcur.fetchall()

# 0 = CONSTRAINT_NAME
# 1 = TABLE_NAME
# 2 = COLUMN_NAME
# 3 = REFERENCED_TABLE_NAME
# 4 = REFERENCED_COLUMN_NAME
# 5 = DATABASE
for row in prep:
    query = "SELECT {1}.{2} AS CHILD_ID, {3}.{4} AS PARENT_ID FROM {5}.{1} LEFT JOIN {5}.{3} ON {1}.{2}={3}.{4} WHERE {3}.{4} IS NULL".format(row[0], row[1], row[2], row[3], row[4], self.database)
    self.dbcur.execute(query)
    results = self.dbcur.fetchall()

    if len(results) > 0:
        for baddata in results:
            bad_data = ({"CONSTRAINT_NAME": row[0], "TABLE_NAME": row[1], "COLUMN_NAME": row[2], "REFERENCED_TABLE_NAME": row[3], "REFERENCED_COLUMN_NAME": row[4], "CHILD_ID": baddata[0], "PARENT_ID": baddata[1], "DATABASE": self.database})
            self.badforeignkeys.append(bad_data)

return(self.badforeignkeys)