-8

I created 2 tables students and course, in course I want to add student_id as foreign key but I am adding the key after creating the table and it is showing error. Need help in solving this thing.

mysql> create table students
(student_id INT PRIMARY KEY, 
first_name VARCHAR(60) NOT NULL, 
last_name VARCHAR(60) NOT NULL, 
email VARCHAR(100));
Query OK, 0 rows affected (0.02 sec)
mysql> INSERT INTO students (student_id, first_name, last_name, email) 
`VALUES (1, 'ana', 'smith', '[email protected]'),
(2, 'ben', 'brown', '[email protected]'), 
(3, 'cirus', 'smith', '[email protected]');
Query OK, 3 rows affected (0.01 sec)
Records: 3  Duplicates: 0  Warnings: 0`

Method1

`mysql> ALTER TABLE course FOREIGN KEY (student_id) REFERENCES students(student_id);`

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 (student_id) REFERENCES students(student_id)' at line 1

Method2 (I added ` on columns )

`mysql> ALTER TABLE course FOREIGN KEY (`student_id`) REFERENCES students(`student_id`);`

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 (student_id) REFERENCES students(student_id)' at line 1

2
  • 5
    ALTER TABLE table_name ADD FOREIGN KEY .. Note ADD keyword Commented Nov 2 at 17:20
  • 1
    Reading the documentation should be your step Commented Nov 2 at 17:56

1 Answer 1

2

You need to say ADD FOREIGN KEY, not just FOREIGN KEY. (See https://www.w3schools.com/mysql/mysql_foreignkey.asp). It will probably look like

ALTER TABLE course
ADD FOREIGN KEY (student_id)
REFERENCES students(student_id);
Sign up to request clarification or add additional context in comments.

1 Comment

+1 but I would avoid referencing w3schools, because that site is often accused of containing incorrect information. I would reference the MySQL manual itself, which has an example of ADD FOREIGN KEY syntax: dev.mysql.com/doc/refman/8.4/en/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.