-1

我有三个表 - 1-FriendShip、2-Users、3-Pages。Friendship 表有 fromUser 和 toUser 列。fromUser 列包含发起好友请求的用户。toUser 包含谁收到了好友请求(灵感来自 Facebook)

我想从 Pages 表中选择与给定用户是朋友的数据,比如“user1”。我可以使用以下查询获取 user1 的朋友:

  SELECT friends.`fromUser` AS `friend`
    FROM friends
    INNER JOIN users
    ON friends.`fromUser` = users.`userid`
    WHERE `friends`.`toUser`='user1'
 UNION
  SELECT friends.`toUser` AS `friend`
    FROM friends
    INNER JOIN users
    ON friends.`toUser` = users.`userid`
    WHERE friends.`fromUser`='user1'

这给了我这样的结果:

好友
user2
user5

等等...

我想选择所有这些用户的页面并按时间戳列降序排列。有人请提供解决方案吗?

4

2 回答 2

0

您可以使用IN,假设您的 Pages 表有一个userid(或等效的)列:

SELECT * FROM Pages
WHERE userid IN (
   -- Your query to retrieve friends of user1
)
ORDER BY `timestamp` DESC
于 2012-10-29T16:17:56.140 回答
0

因此,使用您拥有的查询作为派生表来加入:

SELECT *
FROM pages
INNER JOIN 
(
  SELECT friends.`fromUser` AS `friend`
    FROM friends
    INNER JOIN users
    ON friends.`fromUser` = users.`userid`
    WHERE `friends`.`toUser`='user1'
 UNION
  SELECT friends.`toUser` AS `friend`
    FROM friends
    INNER JOIN users
    ON friends.`toUser` = users.`userid`
    WHERE friends.`fromUser`='user1'
) AS friends ON pages.user = friends.friend
ORDER BY `timestamp` DESC
于 2012-10-29T16:18:11.987 回答