简体   繁体   中英

Drop a foreign key from a table in mysql

I have created a foreign key without giving it a name for a column in a table. Now i want to remove that column. First i've tried removing the foreign key constraint but there was an error
I've used the following sql command

ALTER TABLE passenger 
DROP FOREIGN KEY bookedBy

The error message

#1091 - Can't DROP 'bookedBy'; check that column/key exists

i've ensured that the column exist.
I have not named the foreign key constraint. Is it possible to remove the foreign key constraint without naming it. Is there any default naming given to the foreign keys.

follow this

  1. Log to phpMyAdmin
  2. Check which field you need to DROP (Ex I will use Product )

在此处输入图片说明

  1. then Select

在此处输入图片说明

  1. UnCheck this checkbox and click YES

在此处输入图片说明

The quickest and dirtiest way is to turn off foreign key checks, drop the table and then turn the checks back on

SET FOREIGN_KEY_CHECKS=0;

drop table mytable

SET FOREIGN_KEY_CHECKS=1;

Run the statement SHOW CREATE TABLE passenger .

The output from that will show the foreign key constraints, as well as the columns in the table. You should be able to figure out the name of the foreign key constraint you want to drop from that.

Or, you can muck with your queries of the tables in information_schema database. It's going to show up in there as well.


Followup

One possible query of information_schema to find the names of the foreign key constraints for a given table:

 SELECT kcu.constraint_schema
      , kcu.constraint_name
  --  , kcu.*
   FROM information_schema.key_column_usage kcu
  WHERE kcu.referenced_table_name IS NOT NULL 
    AND kcu.constraint_schema = 'mydatabase'
    AND kcu.table_name        = 'mytablename'
CREATE TABLE Orders
(
  O_Id int NOT NULL,
  OrderNo int NOT NULL,
  P_Id int,
  PRIMARY KEY (O_Id),
  FOREIGN KEY (P_Id) REFERENCES Persons(P_Id)
)

also you can add foreign key like this

ALTER TABLE Orders
ADD FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)

and delete

ALTER TABLE Orders
DROP FOREIGN KEY fk_PerOrders

How to find foreign key in my table

   SELECT
         TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME,
REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME
    FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
    WHERE
      REFERENCED_TABLE_NAME = '<table>';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM