我有三张桌子--1-FriendShip,2-Users,3-pages。 友谊表有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'
这给了我这样的结果:
友
用户2
USER5
依旧......
我想选择所有这些用户的页面,并按时间戳列按降序排序。有人请提供解决方案吗?
答案 0 :(得分:0)
您可以使用IN
,假设您的Pages表格包含userid
(或等效)列:
SELECT * FROM Pages
WHERE userid IN (
-- Your query to retrieve friends of user1
)
ORDER BY `timestamp` DESC
答案 1 :(得分: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