在SQL语句中将NOT IN替换为LEFT JOIN

时间:2014-03-16 08:09:26

标签: mysql sql database

我写了两个工作正常的查询,但它们真的很慢:

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))

我尝试将NOT IN替换为INNER JOINLEFT JOIN,但到目前为止我没有尝试过任何工作。

以下是表格的架构:

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

 - id (primary key)
 - first_name
 - last_name

stars_in_movies

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

提前谢谢。

3 个答案:

答案 0 :(得分:4)

试试这个:

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

第二个查询

  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

答案 1 :(得分:1)

试试这个:

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;

这是 example

答案 2 :(得分:0)

我知道我晚会很晚,但这可能对某人有帮助-

使用NOT IN(缓慢)查询

Select I.InquiryId,I.InquirySubject,I.CreateDt,I.SendTo,I.[From],U.Email as SendBy
From Inquiries I  
Inner Join Users U  
ON I.[From] = U.UserID  
Where I.InquiryId Not In (Select InquiryId from InquiryReply)  
And I.InquiryStatusId  <> 5  
And DATEDIFF(day, I.CreateDt, getdate()) >=10  

使用左联接查询(更快)

 Select I.InquiryId,I.InquirySubject,I.CreateDt,I.SendTo,I.[From],U.Email as SendBy  
  From Inquiries I  
  Left Outer Join InquiryReply IR
  On I.InquiryId = IR.InquiryId
  Inner Join Users U
  ON I.[From] = U.UserID
  Where IR.InquiryId Is NULL
  And I.InquiryStatusId  <> 5  
  And DATEDIFF(day, I.CreateDt, getdate()) >=10