Let's say I have three tables with the following data:
CREATE TABLE movies ( movie_id INT, movie_name VARCHAR(255), PRIMARY KEY (movie_id) ); CREATE TABLE movie_ratings ( movie_rating_id INT, movie_id INT, rating_value TINYINT, PRIMARY KEY (movie_rating_id), KEY movie_id (movie_id) ); CREATE TABLE movie_actors ( movie_actor_id INT, movie_id INT, actor_id INT, PRIMARY KEY (movie_actor_id), KEY movie_id (movie_id) ); INSERT INTO movies VALUES (1, 'Titanic'),(2,'Star Trek'); INSERT INTO movie_ratings VALUES (1,1,5),(2,1,4),(3,1,5); INSERT INTO movie_actors VALUES (1,1,2),(2,2,2);
If I wanted to get the average rating and number of participants for each movie, I could do it using JOINs :
SELECT m.movie_name, AVG(rating_value) AS avgRating, COUNT(actor_id) AS numActors FROM movies m LEFT JOIN movie_ratings r ON m.movie_id = r.movie_id LEFT JOIN movie_actors a ON m.movie_id = a.movie_id GROUP BY m.movie_id;
Let me request this request A. Request A can be rewritten using USING as follows:
SELECT m.movie_name, AVG(rating_value) AS avgRating, COUNT(actor_id) AS numActors FROM movies m LEFT JOIN movie_ratings r USING (movie_id) LEFT JOIN movie_actors a USING (movie_id) GROUP BY m.movie_id;
Call this request B.
Both of these queries return 1 as numActors for the movie Star Trek. Therefore, modify this query a bit:
SELECT m.movie_name, AVG(rating_value) AS avgRating, COUNT(actor_id) AS numActors FROM movies m LEFT JOIN movie_ratings r ON m.movie_id = r.movie_id LEFT JOIN movie_actors a ON r.movie_id = a.movie_id GROUP BY m.movie_id;
Let me call this query C. Instead of doing m.movie_id = a.movie_id I now do r.movie_id = a.movie_id . For a query, C numActors = 0.
My questions:
- How to write a C query using
USING ? Can I? - Is
USING essentially ON with the current table and the table specified in FROM ? - If the answer to # 2 is yes, then what does
USING do when an implicit JOIN is used and several tables are in FROM ?