Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query to exclude certain values from table

Tags:

sql

enter image description here

Hi everyone I am in the process of building a room allocating system that checks if a room is available on a given date. There are about 20 unique room ids and I've just included as snippet of several above.

So for example if the user types in the date of 2012-01-01 I would want the room_id of 1 to be excluded from the results because as seen above it has been already booked for that date.

In a sense any match found between the user's in-putted date should cause the entire list of corresponding room_id's to be excluded from the list.

I used the below SQL query:

SELECT DISTINCT room_id
FROM room_booking
WHERE date_booked<>'$date'

Unfortunately it doesn't work because although it excludes the result for a single row, it includes the rest of the results for a given room_id?

like image 453
methuselah Avatar asked Mar 18 '12 09:03

methuselah


People also ask

How do you exclude a value in SQL?

To exclude multiple values to be fetched from a table we can use multiple OR statements but when we want to exclude a lot of values it becomes lengthy to write multiple AND statements, To avoid this we can use the NOT IN clause with the array of values that need to be excluded with the WHERE statement.

How do I exclude a character in SQL?

[^] Wildcard to exclude characters - SQL Server (Transact-SQL) | Microsoft Learn.


2 Answers

Not tried this, but here goes

SELECT DISTINCT room_id
FROM room_booking
WHERE room_id NOT IN 
    (SELECT DISTINCT room_id
     FROM room_booking
     WHERE date_booked = '$date'
    )
like image 178
Chetter Hummin Avatar answered Nov 03 '22 23:11

Chetter Hummin


You could use a NOT EXISTS

SELECT DISTINCT room_id
  FROM room_booking rb1
 WHERE NOT EXISTS( SELECT 1
                     FROM room_booking rb2
                    WHERE rb2.date_booked = <<date>>
                      AND rb2.room_id     = rb1.room_id )

or a NOT IN

SELECT DISTINCT room_id
  FROM room_booking
 WHERE room_id NOT IN (SELECT room_id
                         FROM room_booking rb2
                        WHERE rb2.date_booked = <<date>>)
like image 24
Justin Cave Avatar answered Nov 04 '22 00:11

Justin Cave