所以我希望能够展示出租最昂贵的电影和租来最便宜的电影。基本上我想要显示电影标题及其价格。现在,我可以通过此查询获得最高和最低的租金价格:
SELECT MAX(rental_rate) as MaxRate, MIN(rental_rate) as MinRate
FROM film;
但是,如何编辑上面的查询以显示与其费率相关的电影标题?
我也尝试过:
SELECT title (SELECT MAX(rental_rate) FROM film as MaxRate),
(SELECT MIN(rental_rate) FROM film as MinRate)
FROM film;
但那没用。
有什么建议吗?
答案 0 :(得分:2)
在我在评论中提到的问题中可以找到一个正确的解决方案,但它有点复杂。我认为另一个更简单的解决方案是ORDER BY
评分并使用LIMIT
获得1条记录。您可以使用UNION
组合两个类似的查询来获得最低和最高的费率:
(SELECT title, rental_rate
FROM film
ORDER BY rental_rate
LIMIT 1)
UNION
(SELECT title, rental_rate
FROM film
ORDER BY rental_rate DESC
LIMIT 1)
也可以使用 UNION ALL
,但如果表格只包含一部电影,则可以获得相同的标题。
请注意,此查询将返回一个最低费率标题和一个最高费率标题。如果您希望所有标题分享最低或最高费率,则您需要that other solution。
答案 1 :(得分:0)
您想要的是具有不同条件的两行,因此请将它们分开:
(SELECT title, rental_rate, "most expensive" as which_title
from film
ORDER BY rental_rate DESC LIMIT 1)
UNION ALL
(SELECT title, rental_rate, "least expensive" from film
ORDER BY rental_rate ASC LIMIT 1)
答案 2 :(得分:0)
如果您想要最低和最高费率及其标题,您也可以使用以下查询:
select title, (SELECT MAX(rental_rate) FROM film) from film
where rental_rate=(SELECT MAX(rental_rate) FROM film)
union
select title, (SELECT MIN(rental_rate) FROM film) from film
where rental_rate=(SELECT MIN(rental_rate) FROM film)