1

嗨,我目前正在编写一些代码,在从数据库中检索结果之前需要一个 if。

情况是,如果interacterID 不为NULL,则按它过滤,见下文

SELECT *
FROM status
WHERE type != "3"
AND userID = "'.$userID.'"
AND 
(
    interacterID IN ( #IF interacterID is null I want to skip this AND
        SELECT userID
        FROM userFriends
        WHERE (
            userFriends.userID = "'.$currentUserID.'"
            OR userFriends.interacterID = "'.$currentUserID.'"
        )
        AND status = "1"
    )
)
ORDER BY addedDate DESC
LIMIT 1

在此先感谢您的帮助。

4

2 回答 2

2

如果我没看错,我不确定你是否需要一个 IF (可以这样做)。简单的 IS NULL 和 OR 可用于两种情况:

SELECT *
FROM status
WHERE type != "3"
AND userID = "'.$userID.'"
AND 
(
    interacterID IS NULL OR interacterID IN (
        SELECT userID
        FROM userFriends
        WHERE (
            userFriends.userID = "'.$currentUserID.'"
            OR userFriends.interacterID = "'.$currentUserID.'"
        )
        AND status = "1"
    )
)
ORDER BY addedDate DESC
LIMIT 1    
于 2012-10-22T10:47:28.660 回答
1
SELECT *
FROM status
WHERE type != "3"
AND userID = "'.$userID.'"
AND 
(
interacterID IS NOT NULL  (
    SELECT userID
    FROM userFriends
    WHERE (
        userFriends.userID = "'.$currentUserID.'"
        OR userFriends.interacterID = "'.$currentUserID.'"
    )
    AND status = "1"
)
  )
  ORDER BY addedDate DESC
  LIMIT 1  

如果interacterID 为null,则代码不会执行

于 2012-10-22T10:50:49.330 回答