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
ALTER TABLE table_name ADD FOREIGN KEY ..Note ADD keyword