首页 > 解决方案 > sql:获取一个单列表,从另一个表按列排序

问题描述

我有相互连接的表。

movies (main, parent) : id | title | year
people (child) : people_id | name | birthyear
ratings (child) : movie_id | rating | votes
stars (child) : movie_id | person_id

我需要进行查询并从表“movies-people-stars”中获取单列输出,并从表“rating”中按列排序,而不将“rating”列加入我的输出。

我的代码:

SELECT title from movies
where id in (select movie_id from stars
         where person_id in(select id from people where name = "Chadwick Boseman"))LIMIT 5;

它返回 Chadwick Boseman 播放的所有电影的标题。我需要按评级订购它们。怎么做?

标签: sqlcs50

解决方案


尽管如果没有连接,这永远不会完成,因为它是家庭作业,您可以ratingsORDER BY子句中对表使用相关子查询:

select m.title
from movies m
inner join stars s on s.movie_id = m.id
inner join people p on p.people_id = s.person_id
where p.name = 'Chadwick Boseman'
order by (select r.rating from ratings r where r.movie_id = m.id) desc
limit 5

您还可以使用查询并添加ORDER BY子句:

select m.title 
from movies m
where m.id in (
  select movie_id 
  from stars
  where person_id in(
    select id 
    from people 
    where name = 'Chadwick Boseman'
  )
)
order by (select r.rating from ratings r where r.movie_id = m.id) desc
limit 5;

推荐阅读