I'm getting ready to populate a couple of tables in a movie database I have created. The Movies
table has already been created. It looks like this:
movieid INT NOT NULL PRIMARY KEY
title VARCHAR(50)
link VARCHAR(100)
release_date VARCHAR(10)
It should perhaps be noted that I'm using MySQL-python
and Scrapy
to populate this data in the MySQL
database, but perhaps that doesn't matter.
I have created three additional tables which have not yet been populated: Producers
, Actors
and Directors
. Each of these looks like the other in that there exists id
, name
and movie title
. So Actors
looks like:
actorid INT NOT NULL PRIMARY KEY
actor VARCHAR(40)
title VARCHAR(50) <<<<------ This is the movie title from the Movies tables
Now, I would like to create a table called Movie To Actor
which holds the movieid
from the Movie
table and the actorid
from the Actor
table and not have the title
column existing in the Actors
table.
I figure there are two ways to do this:
First Way:
Get all of the data into the Actors
table with title
acting as a foreign key
and to THEN create the Movie To Actor
table, adding the appropriate ids
where movies.title
is equal to Actors.title
and to then drop the title
column from Actors
.
Second way:
Do this as I am populating the data. First create the Movie to Actor
table, set up key constraints and set this to auto update as the data is added to Actors
table. I would prefer this as it makes things significantly easier and I think is stylistically better. Was hoping someone could instruct me on how I would go about doing this. I think I can figure out how to extrapolate instructions in MySQL
into MySQL-python
, but would need help on how to do the former.
A couple points first off:
For the first method you mentioned, you actually can first create the movie_actor table and then populate the existing data:
INSERT INTO movie_actor (movieid, actorid) SELECT movieid, actorid FROM movies INNER JOIN actors ON actors.title=movies.title;
For the second, you can use a trigger:
delimiter //
CREATE TRIGGER add_actor
AFTER INSERT ON actors
FOR EACH ROW BEGIN
SET @movieid = (SELECT movieid FROM movies WHERE title=NEW.title);
IF @movieid IS NOT NULL THEN
INSERT INTO movie_actor (movieid, actorid) VALUES (@movieid, NEW.actorid);
END IF;
END;
//
delimiter ;
I'd suggest option 1 followed by having whatever form you're using to populate these tables to populate the movie_actor table independently (eg after adding an actor, you can set whatever movies he/she was in, merely adding a mapping to the movie_actor table). Then if you want to get a list of movies for an actor you can just
SELECT title FROM movie_actor
INNER JOIN movies ON movies.movieid=movie_actor.movieid
WHERE actorid=????
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.