使用EXISTS用IN编写查询

时间:2017-09-03 11:30:14

标签: mysql sql database

我目前正在学习SQL,而我正在尝试使用INEXISTS重新编写查询,但似乎没有给我正确答案。 问题是:

对于数据库中当前最低(最少的星星)的每个评级,返回评论者姓名,电影标题,明星数量

架构:

  • 电影(mID,标题,年份,导演)

  • 审稿人(rID,姓名)

  • 评级(rID,mID,stars,ratingDate)

我的查询是:

Select distinct rew.name, m.title, r.stars
from movie m join rating r on m.mID = r.mID 
join reviewer rew on r.rID = rew.rID
where r.stars in (Select min(stars) from rating)

我试图通过将子查询与外部查询相结合来编写is with exists。我尝试了所有不同的密钥,但到目前为止还没有任何工作。

2 个答案:

答案 0 :(得分:2)

因此,您首先需要获得每部电影的最低评分,例如:

SELECT mID, MIN(stars) AS stars
FROM rating 
GROUP BY mID;

然后,再次与rating表联系,以获取审稿人ID,例如:

SELECT r.rID, a.mID, a.stars
FROM rating r JOIN (
    SELECT mID, MIN(stars) AS stars
    FROM rating 
    GROUP BY mID
) a ON r.MID = a.mID and r.stars = a.stars;

现在,您可以使用Movie和Reviewer表加入上述查询以获取标题,例如:

SELECT m.title, re.name, b.stars
FROM movie m JOIN (
    SELECT r.rID, a.mID, a.stars
    FROM rating r JOIN (
      SELECT mID, MIN(stars) AS stars
      FROM rating 
      GROUP BY mID
    ) a ON r.MID = a.mID and r.stars = a.stars
) b
ON m.mID = b.mID
JOIN reviewer re ON re.rID = b.rID;

答案 1 :(得分:2)

我想使用NOT EXISTS可以完成这项工作

SELECT distinct rew.name, m.title, r.stars
FROM movie m 
JOIN rating r ON m.mID = r.mID 
JOIN reviewer rew ON r.rID = rew.rID
WHERE NOT EXISTS
(
    SELECT 1 
    FROM Rating r2
    WHERE r2.stars > r.stars
)