NOT IN FUNCTION in MySQL

1.3k views Asked by At

I am having a problem with a sql query

Here is my query:

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)))

The problem is that when the second select returns null, it shows the following error:

#1241 - Operand should contain 1 column(s)

Can anybody help me?

EDIT

When I run this query it shows all the rows even the one which includes inside of the second select I don't know why?

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')))
2

There are 2 answers

0
Paul Bellora On BEST ANSWER

I imagine you want something like

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

for the sub-select, since room_id is what you are matching on with the NOT IN operator.

1
xQbert On
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 must be limited to the same list of values in the where so * won't work unless reservations only has a 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)))