mysql:如果表B中不存在,则从表A中选择所有项目

时间:2011-01-11 17:56:32

标签: mysql select not-exists

我在从表a(id,room_name)中选择值时遇到问题,其中表b中没有相应的事件(room_id,room_start,room_finish)

我的查询看起来跟着

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

表a包含多个房间,表b包含房间事件 如果时间戳内的任何房间都有任何活动,我将无法获得任何结果。我期待所有房间都没有活动。

2 个答案:

答案 0 :(得分:26)

以下是您想要做的原型:

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

这里,假设id是两个表中的PK和FK。你应该相应调整。另请注意,在这种情况下比较PK和FK很重要。

因此,以下是您的查询的样子:

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

如果需要,可以通过在mysql客户端中执行查询来检查查询的各个部分。例如,您可以确保以下内容是否返回任何记录:

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

如果没有,你找到了罪魁祸首,并采取相应的行动与其他部分:)

答案 1 :(得分:0)

您缺少仅使用该会议室的活动。这是通过匹配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')