Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace NOT IN with LEFT JOIN in SQL statement

I wrote two queries which are working fine, but they are really really slow:

SELECT director
FROM movies
WHERE id NOT IN (SELECT movie_id FROM stars_in_movies WHERER star_id = %s);

SELECT first_name, last_name
FROM stars
WHERE id NOT IN (SELECT star_id
                 FROM stars_in_movies
                 WHERE movie_id IN(SELECT movie_id
                                   FROM stars_in_movies
                                   WHERE star_id = %s))

I tried to replace NOT IN with INNER JOIN and LEFT JOIN but nothing I have tried worked so far.

Following is schema for the tables:

movies:

 - id (primary key),
 - title (title of the movie), 
 - year (year of release)
 - director (director of the movie)

stars:

 - id (primary key)
 - first_name
 - last_name

stars_in_movies:

 - movie_id, 
 - star_id (movie_id and star_id both are foreign keys here)

Thank you in advance.

like image 345
Yash Patel Avatar asked Mar 16 '14 08:03

Yash Patel


2 Answers

Try this:

SELECT m.director 
FROM movies m
LEFT JOIN stars_in_movies sm ON m.id = sm.movie_id
WHERE sm.movie_id IS NULL 
AND sm.star_id = %s

the second query

  SELECT first_name, last_name
  FROM stars s
  LEFT JOIN stars_in_movies sm
  ON sm.star_id = s.id
  WHERE sm.star_id IS NULL
  AND star_id = %s
like image 132
echo_Me Avatar answered Sep 19 '22 12:09

echo_Me


Try this:

select t1.director
from movies t1 left outer join stars_in_movies t2 on t1.id = t2.movie_id
where t2.movie_id is null;

select t1.first_name, t1.last_name
from stars t1 left outer join stars_in_movies t2 on t1.id = t2.star_id
where t2.star_id is null;

here is an example

like image 41
Hamidreza Avatar answered Sep 19 '22 12:09

Hamidreza