0

I have a database, I used these commands :

CREATE TABLE APPOINTMENT (app_id INT(5) NOT NULL, app_doctor INT(5) NOT NULL, app_date DATE, PRIMARY KEY (app_id));

CREATE TABLE APPPATIENTS (patient_ssn INT(10) NOT NULL, patient_name VARCHAR(20) NOT NULL, sex CHAR(1) NOT NULL, appointment_id INT(5), PRIMARY KEY (patient_ssn), UNIQUE (appointment_id));

ALTER TABLE APPPATIENTS ADD FOREIGN KEY (appointment_id) REFERENCES APPOINTMENT(app_id) ON DELETE CASCADE;

Now, I want to delete foreign key appointment_id in appPatients table :

ALTER TABLE apppatients DROP FOREIGN KEY appointment_id;

But I got an error :

Can't drop 'appointment_id'; check that column/key exists. 

It is there! How can it give that error? What am I doing wrong?

berkc
  • 525
  • 3
  • 9
  • 21

1 Answers1

0

I tried to create a database with your code and I notice the foreign key name appears different from appointment_id: reading with more attention the command definition, I notice that when you write

ADD FOREIGN KEY (appointment_id)

you are only saying the column on which the constraint will be created, not its name.
You can read the specifications here: SQL FOREIGN KEY Constraint on ALTER TABLE

So, if you want to specify the name of the key, you have to write, for example:

alter table APPPATIENTS 
ADD CONSTRAINT appointment_key 
FOREIGN KEY (appointment_id) 
REFERENCES appointment(app_id) ON DELETE CASCADE;

And so you know the name of the foreign key you created (appointment_key in this case).
If you want to know the foreign key name generated by mysql you can use the command

show create table APPPATIENTS;

that shows the complete table definition.

lyisia
  • 144
  • 8