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

青春壹個敷衍的年華 提交于 2019-11-29 05:53:53

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

You are missing to use only the events from that room. That is done by matching the id.

SELECT id, room_name FROM rooms r
WHERE NOT EXISTS 
(SELECT * FROM room_events re
      WHERE r.id = re.room_id AND
      room_start BETWEEN '1294727400' AND '1294729200' 
      OR 
      room_finish BETWEEN '1294727400' AND '1294729200')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!