简体   繁体   中英

Join 3 different tables in SQL

I am working on three different tables that are related for actors, movies they played in and what they were cast as in the movie. My current problem is I cannot get the Movie title to correlate correctly with the Actors Name and the role they played. Here is my SQL syntax. And a screenshot of my output. Obviously the movie title does not match with the actor. For instance Robert Loggia and AlPacino should both have the movie Scarface next to them. What am I missing here?

当前结果

SELECT a.fname, lname, c.characterRole, m.title, salary
FROM Actor a, Castings c, Movie m 
where a.actorID = c.actorId and a.actorID = m.movieId

电影桌

First, never use commas in the FROM clause. Always use proper, explicit, standard JOIN syntax.

The query you want looks like:

SELECT a.fname, lname, c.characterRole, m.title, salary
FROM Actor a JOIN
     Castings c
     ON a.actorID = c.actorId JOIN
     Movie m 
     ON c.movieId = m.movieId;

Equating actorId and movieId doesn't make sense. Movie ids should be connected to movie ids.

I assume that the Castings table has a movieId to be linked to the Movie table

SELECT 
a.fname AS FirstName, 
a.lname AS LastName, 
c.characterRole, 
m.title, 
c.salary
FROM Movie m
JOIN Castings c ON c.movieId = m.movieId
JOIN Actor a ON a.actorID = c.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM