sql:获取一个单列表,从另一个表按列排序

beq87vna  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(379)

我有相互连接的table。

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;

它返回查德威克·博斯曼所演电影的所有片名。我需要按等级订购。怎么做?

lh80um4z

lh80um4z1#

尽管没有联接永远无法完成这项工作,但因为这是一项家庭作业,所以可以对表使用相关子查询 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;
v64noz0r

v64noz0r2#

您需要在选择列表中包含该列,以便按该列排序。order by按指定列的顺序对输出进行排序。另外,为什么不能像下面这样对查询使用连接呢。

SELECT m.title,d.rating 
FROM movies m
JOIN stars s ON s.movie_id = m.id
JOIN people p ON p.id = s.person_id 
JOIN tbl d ON d.xx = z.yy  ----- JOIN the table d here and use it in select . replace z,xx and yy with actual table name and columns.
WHERE p.name = "Chadwick Boseman" 
ORDER BY d.rating
LIMIT 5

更新*-它可能工作,但无法测试,因为我无法访问实际的数据和表。

SELECT m.title
FROM movies m
JOIN stars s ON s.movie_id = m.id
JOIN people p ON p.id = s.person_id
WHERE p.name = 'Chadwick Boseman'
AND m.id in (SELECT top 5 movie_id 
             FROM ratings r
             WHERE r.movie_id = m.id 
             ORDER BY ratings desc)

相关问题