MySQL foreign key constraint is replaced only if it exists

It’s been looking for almost an hour, and I can’t believe that I still do not understand how to do it. I found this:

Migration restrictions only if it exists in mysql server 5.0

but the links offered there are not enough information to get me there. Can someone suggest an example with code, please?

UPDATE

Sorry that the original question was not clear, but I was hoping for a way to do this only in SQL, without using any application programming.

+6
source share
1 answer

php code example:

function removeFK(PDO $pdo, $dbName, fkName) { echo "Removing foreign key '$fkName' from database: $dbName\t"; $exists = $pdo->query(" SELECT TRUE FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE = 'FOREIGN KEY' AND TABLE_SCHEMA = '$dbName' AND CONSTRAINT_NAME = '$fkName' ")->fetchColumn(); if ($exists === false) { echo " [SKIPPING] (FK does not exist)\n"; return false; } $pdo->query("USE $dbName"); $pdo->query(" ALTER TABLE intelligence_webpage_has_region_keyword DROP FOREIGN KEY $fkName"); echo "[OK]\n"; return true; } 
+2
source

Source: https://habr.com/ru/post/957552/


All Articles