SQL 3 个表要加入

SQL 3 tables to join

Table film

film_id title description rental_rate

Table category

category_id name last_update

Table film_category

film_id category_id last_update

我有 SQL 到 select 5 个最喜欢的出租率

SELECT title, rental_rate FROM film ORDER BY rental_rate DESC LIMIT 5

根据上面的SQL,如何select 4个最喜欢的类别?

我要的结果就是category.name

试试这个:

select * from (select t3.name,sum(t1.rental_rate) as rate from film as t1
inner join film_category as t2 on t1.film_id=t2.film_id
inner join category as t3 on t2.category_id=t3.category_id
group by t2.category_id) as detail order by rate DESC LIMIT 5

可能您正在寻找这个:

SELECT c.name FROM film a
INNER JOIN film_category b ON a.film_id=b.film_id
INNER JOIN category c ON b.category_id=c.category_id
WHERE a.rental_rate IN 
(
    SELECT TOP (5) rental_rate FROM film    
    ORDER BY rental_rate DESC
)