我有3個房間房間,酒店,城市,我如何選擇10個最便宜的房間和每個城市的hotel_id 可能爲每個城市執行子查詢?每個城市10個最便宜的房間
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;
這個方法返回錯誤的排序˚F或ROW_NUMBER < 6(我的初始化數據)
也許你可以描述_hotel_ _room_和_City_的架構? – gideon 2011-04-13 15:31:44
這是Kynth認爲的實際功課嗎?這會影響我的答案,因爲在MySQL中使用用戶變量的最佳方式是使用用戶變量,但作業可能希望您使用子查詢。 – 2011-04-13 15:33:23