1

我在使用 sql 查询时遇到问题

这是我的查询:

SELECT `rooms`.*  
FROM `rooms`  
WHERE (`rooms`.`room_id` NOT IN (
    SELECT * 
    FROM `reservations` `res` 
    WHERE ('2012-05-03' NOT BETWEEN res.expected_checkin_date 
    AND res.expected_checkout_date) 
    AND ('2012-05-08' NOT BETWEEN res.expected_checkin_date 
    AND res.expected_checkout_date)))

问题是当第二个select返回null时,它显示以下错误:

#1241 - Operand should contain 1 column(s)

有谁能够帮助我?

EDIT

当我运行此查询时,它会显示所有行,甚至包括第二行内的行,select 我不知道为什么?

SELECT `rooms`.*, `type`.*, `status`.* FROM `rooms` INNER JOIN `room_types` AS `type` ON `type`.`room_type_id` = `rooms`.`room_type_id` AND `type`.`num_beds` >= 1 AND type.room_type_id=2 INNER JOIN `room_statuses` AS `status` ON `status`.`room_status_id` = `rooms`.`room_status_id` WHERE (`rooms`.`room_id` NOT IN (SELECT `res`.`room_id` FROM `reservations` `res` WHERE (res.expected_checkin_date >= '2012-05-01' AND res.expected_checkin_date < '2012-05-31') AND (res.expected_checkout_date >= '2012-05-31' AND res.expected_checkout_date < '2012-05-31')))
4

2 回答 2

6

我想你想要类似的东西

SELECT `reservations`.`room_id` FROM `reservations`

对于子选择,因为room_id这是您与NOT IN运算符匹配的内容。

于 2012-05-19T16:00:12.270 回答
4
SELECT `rooms`.*  
FROM `rooms`  
WHERE (`rooms`.`room_id` NOT IN (
    SELECT * 
    FROM `reservations` `res` 
    WHERE ('2012-05-03' NOT BETWEEN res.expected_checkin_date 
    AND res.expected_checkout_date) 
    AND ('2012-05-08' NOT BETWEEN res.expected_checkin_date 
    AND res.expected_checkout_date)))

NOT in 必须限制在 where 中的相同值列表,所以 * 将不起作用,除非 reservations 只有一个 room_Id

SELECT `rooms`.*  
FROM `rooms`  
WHERE (`rooms`.`room_id` NOT IN (
    SELECT res.Room_ID 
    FROM `reservations` `res` 
    WHERE ('2012-05-03' NOT BETWEEN res.expected_checkin_date 
    AND res.expected_checkout_date) 
    AND ('2012-05-08' NOT BETWEEN res.expected_checkin_date 
    AND res.expected_checkout_date)))
于 2012-05-19T16:03:36.607 回答