每个城市十个最便宜的房间

时间:2011-04-13 15:28:45

标签: mysql subquery greatest-n-per-group

我有3个房间,酒店,城市,如何为每个城市选择十个最便宜的房间及其hotel_id 可以为每个城市执行子查询吗?

SELECT price, room_id, hotel_id, city_id
    FROM Hotel 
    JOIN  Room USING(hotel_id)
ORDER BY price
LIMIT 10


Scheme
CREATE TABLE `City` (
  `city_id` int(11) NOT NULL AUTO_INCREMENT,
  `city_name` varchar(50) NOT NULL,
  PRIMARY KEY (`city_id`)
) 

CREATE TABLE `Hotel` (
  `hotel_id` int(11) NOT NULL AUTO_INCREMENT,
  `city_id` int(11) NOT NULL,
  `hotel_name` varchar(100) NOT NULL,
   PRIMARY KEY (`hotel_id`),
   CONSTRAINT `Hotel_FK_1` FOREIGN KEY (`city_id`) REFERENCES `City` (`city_id`) ON DELETE CASCADE ON UPDATE CASCADE
)

CREATE TABLE `Room` (
  `room_id` int(11) NOT NULL AUTO_INCREMENT,
  `hotel_id` int(11) NOT NULL,
  `room_name` varchar(255) DEFAULT NULL,
  `room_price1` int(11) DEFAULT NULL,
  PRIMARY KEY (`room_id`),
  CONSTRAINT `Room_FK_1` FOREIGN KEY (`hotel_id`) REFERENCES `Hotel` (`hotel_id`) ON DELETE CASCADE ON UPDATE CASCADE
)

使用子查询进行查询

SELECT 
     r.room_price1, r.room_id, h.hotel_name, c.city_name
FROM Hotel h 
INNER JOIN Room r ON
    h.hotel_id = r.hotel_id
INNER JOIN City c USING(city_id)
WHERE (
   SELECT count(*) from Room as rt
   JOIN Hotel ht using(hotel_id)
   where c.city_id = ht.city_id and rt.room_price1 < r.room_price1 OR (rt.room_price1 = r.room_price1 AND rt.room_id < r.room_id)
) < 3 
ORDER BY c.city_name, h.hotel_id, r.room_price1

如果一些酒店有一些room_price1这个查询返回超过3行的城市,我需要每个城市3个独特的酒店这个查询可以从一个酒店返回3个房间

生病尝试使用用户代码

set @num := 0, @type := '';
select *
from (
   select r.room_price1 pr, r.room_id, h.hotel_name, c.city_name,
      @num := if(@type = city_id, @num + 1, 1) as row_number,
      @type := city_id as dummy
  from Hotel h
  JOIN Room r USING(hotel_id)
  INNER JOIN City c USING(city_id)
  order by city_name, r.room_price1 asc
) as x where x.row_number <=3;

此方法返回row_number&lt;的错误排序6(我的初始数据)

2 个答案:

答案 0 :(得分:2)

有很多关于这个主题的博客文章。

对我来说最有价值的可能是

Xaprb帖子(请参阅“从每个组中选择前N行”一节进行详细说明)

http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/

在你的情况下,这意味着。根据您的需要对此SQL进行建模。

select type, variety, price
from fruits
where (
   select count(*) from fruits as f
   where f.type = fruits.type and f.price < fruits.price
) <= 2;

让我们尝试一下

SELECT 
   r.price, r.room_id, h.hotel_id, h.city_id
FROM Hotel h INNER JOIN Room r ON
  h.hotel_id = r.hotel_id
WHERE (
   select count(*) from Room as rt
   where r.hotel_id = rt.hotel_id and r.price > rt.price
) <= 10;
ORDER BY h.city_id,h.hotel_id,r.price

你可以看到你做了一个子查询来选择所有房间的数量 价格低于当前根的价格,看看是否 计数小于或等于10.

特别注意我是如何改变

f.price < fruits.price

r.price > rt.price

因为在Xaprb的例子中他选择了N个最便宜的水果

希望有所帮助。

BTW Stackoverflow不是用于解决作业。你也应该学习一些自己的东西; - )

答案 1 :(得分:1)

我假设表Room引用了它所属的Hotel

SELECT price, room_id, hotel_id, city_id
    FROM Hotel,Room 
    WHERE Hotel.hotel_id = Room.hotel_id
ORDER BY price GROUP BY city_id
LIMIT 10