我有两张桌子:
我想删除启动用户和target_user都设置为“user_connected = 0”的所有“房间”
我有两个问题:
如何定位这些用户? 显然这个查询不起作用:
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)
)
我希望,如果可能的话,使用相同的查询来删除这些房间(如果我使用第二个查询就没问题,但这意味着每个结果都会触发此查询,这很多.Isn'是否可以一次删除这些房间?
答案 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)
要定位用户,您需要JOIN
表users
两次,一次针对发起用户,另一次针对目标用户:
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