MySQL – syntax examples: create table, primary and foreign keys
Last night I was asked for very basic example how create tables in MySQL and how to set keys up. I want to publish it here maybe it’ll be helpful for somebody, especially for beginners.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
CREATE TABLE MOVIES ( ID INT AUTO_INCREMENT NOT NULL PRIMARY KEY, TITLE VARCHAR(50) ); CREATE TABLE ACTORS ( ID INT AUTO_INCREMENT NOT NULL PRIMARY KEY, FIRST_NAME VARCHAR(20), LAST_NAME VARCHAR(40) ); CREATE TABLE MOVIE_ACTORS ( ID INT AUTO_INCREMENT NOT NULL PRIMARY KEY, MOVIE_ID INT NOT NULL, ACTOR_ID INT NOT NULL, FOREIGN KEY(MOVIE_ID) REFERENCES MOVIES(ID), FOREIGN KEY(ACTOR_ID) REFERENCES ACTORS(ID) ); INSERT INTO ACTORS(FIRST_NAME, LAST_NAME) VALUES ('Marlon', 'Brando'); INSERT INTO MOVIES(TITLE) VALUES('Godfather'); INSERT INTO MOVIE_ACTORS(MOVIE_ID, ACTOR_ID) VALUES(1,1); |