给定这个表达式:
set @userID = 91;
SELECT * FROM table1
WHERE (iduser IN (SELECT iduser1 FROM table2 WHERE iduser2 = @userID)
OR (iduser IN (SELECT iduser2 FROM table2 WHERE iduser1 = @userID)))
使用 EXISTS,您可以将这两个子查询减少为以下内容:
set @userID = 91;
SELECT * FROM table1 x
WHERE EXISTS(
select * from table2 z
where (z.user2 = @userID and iduser1 = x.iduser)
OR (z.user1 = @userID and iduser2 = x.iduser)
)
OR 可能会减慢您的查询速度,它不一定会在 RDBMS 中短路。在这种情况下,您应该尝试使用 CASE WHEN 将其短路。我有一个查询在使用 OR 时需要 5 秒才能执行,但当我将其转换为 CASE WHEN 时需要不到零秒:
set @userID = 91;
SELECT * FROM table1 x
WHERE EXISTS(
select * from table2 z
where
CASE WHEN z.user2 = @userID THEN
IF(z.iduser1 = x.iduser, 1, 0)
CASE WHEN z.user1 = @userID THEN
IF(z.iduser2 = x.iduser, 1, 0)
END = 1
)
布尔表达式自动转换为整数(0(假)或 1(真)),所以你也可以这样做:
set @userID = 91;
SELECT * FROM table1 x
WHERE EXISTS(
select * from table2 z
where
CASE WHEN z.user2 = @userID THEN
z.iduser1 = x.iduser
CASE WHEN z.user1 = @userID THEN
z.iduser2 = x.iduser
END = 1
)
或这个:
set @userID = 91;
SELECT * FROM table1 x
WHERE EXISTS(
select * from table2 z
where
CASE WHEN z.user2 = @userID THEN
z.iduser1 = x.iduser
CASE WHEN z.user1 = @userID THEN
z.iduser2 = x.iduser
END
)
如果你不使用 MySQL,你应该这样做:
set @userID = 91;
SELECT * FROM table1 x
WHERE EXISTS(
select * from table2 z
where
CASE WHEN z.user2 = @userID THEN
CASE WHEN z.iduser1 = x.iduser THEN 1 END
CASE WHEN z.user1 = @userID THEN
CASE WHEN z.iduser2 = x.iduser THEN 1 END
END = 1
)