Search code examples
mysqlforeign-keysconstraintsddl

MySQL: Unable to drop/remove foreign key


Here is what I've tried so far:

mysql> alter table wp_delayedCoupons_visits remove foreign key fk_targets_visits;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'foreign key fk_targets_visits' at line 1

mysql> alter table wp_delayedCoupons_visits drop foreign key fk_targets_visits;
ERROR 1091 (42000): Can't DROP 'fk_targets_visits'; check that column/key exists

And also with backticks

mysql> alter table `wp_delayedCoupons_visits` remove foreign key `fk_targets_visits`;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'foreign key `fk_targets_visits`' at line 1

mysql> alter table `wp_delayedCoupons_visits` drop foreign key `fk_targets_visits`;
ERROR 1091 (42000): Can't DROP 'fk_targets_visits'; check that column/key exists

mysql> show columns in wp_delayedCoupons_visits;

+-------------------+--------------+------+-----+---------+----------------+
| Field             | Type         | Null | Key | Default | Extra          |
+-------------------+--------------+------+-----+---------+----------------+
| visitId           | mediumint(5) | NO   | PRI | NULL    | auto_increment |
| visitorId         | mediumint(9) | NO   |     | NULL    |                |
| urlVisited        | varchar(500) | NO   |     | NULL    |                |
| fk_targets_visits | mediumint(5) | NO   | UNI | NULL    |                |
+-------------------+--------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

Does anyone have an idea what may causing the constraint not to drop or be removed?


Solution

  • You obviously have a column called fk_targets_visits, but not a foreign key constraint even named with a fk_ prefix.

    look up by using

    show create table `wp_delayedCoupons_visits`
    

    if a forign key exists in this table, and then reissue your command by

    alter table `wp_delayedCoupons_visits` drop foreign key fk_coup_visits 
    

    assuming a foreign key name fk_coup_visits really exists.