Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql: select all items from table A if not exist in table B

I am having problem with selecting values from table a (id, room_name) where there are no corresponding events in table b (room_id, room_start, room_finish)

my query looks following

SELECT id, room_name FROM rooms 
WHERE NOT EXISTS 
(SELECT * FROM room_events 
    WHERE room_start BETWEEN '1294727400' AND '1294729200' 
          OR 
          room_finish BETWEEN '1294727400' AND '1294729200')

table a contains multiple rooms, table b contains room events I am getting no results in case there is any event for any of the rooms within the timestamps. I am expecting all rooms having NO events.

like image 362
m1k3y3 Avatar asked Jan 11 '11 17:01

m1k3y3


People also ask

How do you SELECT all records from one table that do not exist in another table in SQL?

How to Select All Records from One Table That Do Not Exist in Another Table in SQL? We can get the records in one table that doesn't exist in another table by using NOT IN or NOT EXISTS with the subqueries including the other table in the subqueries.

How do you SELECT data from one table is not in another?

select [ selecting columns] From table1 Right OUTER JOIN table2 ON(table1. SQL> select e. select [ selecting columns] From table1 Right OUTER JOIN table2 ON(table1. select column_name from table 1 full outer join table 2 on(connection); here all the data from table 1 and table 2 will get retrieved.

Does != Work in MySQL?

The Not Equal operators in MySQL works the same to perform an inequality test between two expressions.

What is the use of <> in MySQL?

The symbol <> in MySQL is same as not equal to operator (!=). Both gives the result in boolean or tinyint(1). If the condition becomes true, then the result will be 1 otherwise 0. Case 1 − Using !=


1 Answers

Here is the prototype for what you want to do:

SELECT * FROM table1 t1
  WHERE NOT EXISTS (SELECT 1 FROM table2 t2 WHERE t1.id = t2.id)

Here, id is assumed to be the PK and FK in both tables. You should adjust accordingly. Notice also that it is important to compare PK and FK in this case.

So, here is how your query should look like:

SELECT id, room_name FROM rooms r
WHERE NOT EXISTS 
(SELECT * FROM room_events re
    WHERE
          r.room_id = re.room_id
          AND
          (
          room_start BETWEEN '1294727400' AND '1294729200' 
          OR 
          room_finish BETWEEN '1294727400' AND '1294729200')
          )

If you want, you check the parts of your query by executing them in mysql client. For example, you can make sure if the following returns any records or not:

SELECT * FROM room_events 
    WHERE room_start BETWEEN '1294727400' AND '1294729200' 
          OR 
          room_finish BETWEEN '1294727400' AND '1294729200'

If it doesn't, you have found the culprit and act accordingly with other parts :)

like image 192
Sarfraz Avatar answered Oct 20 '22 03:10

Sarfraz