PHP MySQL分配在DB中复制的外键

时间:2015-03-16 22:16:45

标签: php mysql database alter-table querying

我有以下代码:

$fkQuery = "SELECT TABLE_CONSTRAINTS.TABLE_NAME, KEY_COLUMN_USAGE.COLUMN_NAME, KEY_COLUMN_USAGE.REFERENCED_TABLE_NAME, KEY_COLUMN_USAGE.REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS RIGHT OUTER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE ON INFORMATION_SCHEMA.TABLE_CONSTRAINTS.CONSTRAINT_NAME = INFORMATION_SCHEMA.KEY_COLUMN_USAGE.CONSTRAINT_NAME WHERE INFORMATION_SCHEMA.KEY_COLUMN_USAGE.CONSTRAINT_NAME <> 'PRIMARY' AND INFORMATION_SCHEMA.TABLE_CONSTRAINTS.CONSTRAINT_TYPE = 'FOREIGN KEY' AND INFORMATION_SCHEMA.TABLE_CONSTRAINTS.TABLE_SCHEMA = '".$dbName."';"; 

$fkQueryResult = $newLink->query($fkQuery); 

$a = 0;

while($fkey = $fkQueryResult->fetch(PDO::FETCH_ASSOC))
{
    $testF[] = $fkey; 
    $assocF = $testF[$a]; 

    $newTableName = $assocF['TABLE_NAME']; 
    $newColumnName = $assocF['COLUMN_NAME']; 
    $newRefTableName = $assocF['REFERENCED_TABLE_NAME']; 
    $newRefColumnName = $assocF['REFERENCED_COLUMN_NAME']; 

    $addFkToTable = "ALTER TABLE " . $newDbName . "." . $newTableName . " ADD FOREIGN KEY (" . $newColumnName . ") REFERENCES " . $dbName . "." . $newRefTableName . "(" . $newRefColumnName . ");";

    echo $addFkToTable . "\n"; 

    $newLink->query($addFkToTable); 

    $a++; 
}

这将从旧数据库中的旧表中选择所有外键引用,以便可以将它们中继到新数据库表中。这是有效的,除了它将每个外键关系加倍。因此,例如,我有TableA(columnA)引用TableB(columnB)。当我对数据库运行fkQuery时,它将返回fk存在,但会将其列出两次。关于如何补救的任何建议?

0 个答案:

没有答案