gpt4 book ai didi

MySQL - 具有 AND 条件的 2 个 block 中具有 OR 条件的接头

转载 作者:行者123 更新时间:2023-11-29 20:04:59 24 4
gpt4 key购买 nike

此查询适用于大多数服务器,但不适用于其他服务器。它会导致CPU过载或结果为空。

SELECT 
M.id,
M.sender,
M.recipient,
M.date,
M.read,
U.ID
FROM
msg M,
users U
WHERE
(M.recipient='".$user_login."' and
M.deleted!=1 and
U.user_login=M.sender)
or
(M.sender='".$user_login."' and
M.deleted!=2 and
U.user_login=M.recipient)
ORDER BY M.date DESC

我对此进行了更改,但同样的问题:

SELECT 
M.id,
M.sender,
M.recipient,
M.date,
M.read,
U.ID
FROM
msg M
LEFT JOIN
users U
ON
(M.recipient='".$user_login."' and
M.deleted!=1 and
U.user_login=M.sender)
or
(M.sender='".$user_login."' and
M.deleted!=2 and
U.user_login=M.recipient)
ORDER BY M.date DESC

我认为问题在于有两种情况的联合条款。

我认为“id”和“ID”不会出现大小写问题。

当然,我可以进行 2 个查询,但肯定有一种方法可以通过单个查询来完成此操作。

最佳答案

JOIN 条件中的 OR 听起来是一个可怕的主意。通常 UNION 是更好的解决方案:-

SELECT 
M.id,
M.sender,
M.recipient,
M.date AS msg_date,
M.read,
U.ID
FROM msg M
INNER JOIN users U
ON U.user_login=M.sender
WHERE M.recipient='".$user_login."'
AND M.deleted!=1
UNION
SELECT
M.id,
M.sender,
M.recipient,
M.date AS msg_date,
M.read,
U.ID
FROM msg M
INNER JOIN users U
ON U.user_login=M.recipient
WHERE M.sender='".$user_login."'
AND M.deleted!=2
ORDER BY msg_date DESC

关于MySQL - 具有 AND 条件的 2 个 block 中具有 OR 条件的接头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40376341/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com