我有一个查询来获取用户的朋友,还有一个用于获取用户发布的所有帖子作为状态,现在我需要将它们合并。
朋友:
SELECT CASE WHEN userID=$session THEN userID2 ELSE userID END AS friendID
FROM friends
WHERE userID=$session OR userID2=$session
然后用户帖子:
SELECT * FROM posts
WHERE toID=fromID AND state='0'
ORDER BY id DESC LIMIT 10
所以两者都应该合作。来自第一个查询的friendID应该等于ID或fromID,因为它们都需要相同而无关紧要。
答案 0 :(得分:2)
这些帖子的第二个条件是他们来自朋友。所以:
SELECT * FROM posts
WHERE toID=fromID AND state='0' AND toID IN
(SELECT CASE WHEN userID=$session THEN userID2 ELSE userID END AS friendID
FROM friends
WHERE userID=$session OR userID2=$session)
ORDER BY id DESC LIMIT 10
答案 1 :(得分:0)
您应该使用JOIN
:
SELECT
CASE
WHEN userID=$session THEN userID2
ELSE userID
END AS friendID,
posts.*
FROM friends
JOIN posts on posts.toID = friends.friendID
WHERE (userID=$session OR userID2=$session)
AND toID=fromID
AND state='0'
ORDER BY id DESC LIMIT 10