使用单个查询选择和删除

时间:2012-05-08 01:25:09

标签: mysql select optimization sql-delete

我有两张桌子:

  • 用户(user_id,user_connected)
  • 房间(room_id,room_initiating_user_id,room_target_user_id)

我想删除启动用户和target_user都设置为“user_connected = 0”的所有“房间”

我有两个问题:

  1. 如何定位这些用户? 显然这个查询不起作用:

    SELECT room_id
    FROM rooms,users
    WHERE
    ( 
     (room_target_user_id=user_id) AND (user_connected=0)
    )                   
    AND
    (                
     (room_initiating_user_id=user_id) AND (user_connected=0)
    )
    
  2. 我希望,如果可能的话,使用相同的查询来删除这些房间(如果我使用第二个查询就没问题,但这意味着每个结果都会触发此查询,这很多.Isn'是否可以一次删除这些房间?

3 个答案:

答案 0 :(得分:5)

delete from rooms
where room_initiating_user_id in (select user_id from users where user_connected = 0)
  and room_target_user_id in (select user_id from users where user_connected = 0)

答案 1 :(得分:0)

要定位用户,您需要JOINusers两次,一次针对发起用户,另一次针对目标用户:

SELECT room.room_id
FROM rooms room
INNER JOIN users initiating
ON room.room_initiating_user_id = initiating.user_id
INNER JOIN users target
ON room.room_target_user_id = target.user_id
WHERE initiating.user_connected=0 AND target.user_connected=0

要删除这些房间,您可以将上述内容用作子查询:

DELETE FROM rooms
WHERE room_id IN (
    SELECT room.room_id
    FROM rooms room
    INNER JOIN users initiating
    ON room.room_initiating_user_id = initiating.user_id
    INNER JOIN users target
    ON room.room_target_user_id = target.user_id
    WHERE initiating.user_connected=0 AND target.user_connected=0
)

答案 2 :(得分:0)

首先,要选择这些房间,您需要两次加入用户表:

SELECT r.room_id
FROM rooms r 
    JOIN users tgt ON r.room_target_user_id = tgt.user_id
    JOIN users ini ON r.room_initiating_user_id = ini.user_id
WHERE tgt.user_connected = 0 AND ini.user_connected = 0

注意:为表用户使用两个不同的别名,以便区分这两个连接。另外,我使用JOIN语法,而不是不鼓励使用旧的逗号连接

要删除房间,您需要进行多表删除:

DELETE r
FROM rooms r 
    JOIN users tgt ON r.room_target_user_id = tgt.user_id
    JOIN users ini ON r.room_initiating_user_id = ini.user_id
WHERE tgt.user_connected = 0 AND ini.user_connected = 0