我正在使用两张桌子。第一个(好友列表),包含朋友列表中的用户和包含用户基本数据的其他表(成员)。
好友列表如下:
id | myid | date | user
-----------------------------------------
001 | 50624 | 2010-01-01 | 32009
002 | 41009 | 2010-05-05 | 50624
003 | 50624 | 2010-03-02 | 23007
“myid”列包含将其他用户(来自“user”列的用户)添加到其frindlist的成员。我想获取我已添加到列表中的所有用户的列表以及将我添加到他们的朋友列表中的用户。
在此示例中,如果我的ID为50624,则列表如下所示:
| allfriends |
---------------
32009
41009
23007
然后我需要使用表“members”中的数据检查“allfriend”列表中的所有用户。我想只获得状态为1的用户。
成员表看起来像:
id | status | photo
--------------------------------
32009 | 0 | 1.jpg
41009 | 1 | 2.jpg
23007 | 1 | 3.jpg
这个mysql查询应该如何? 谢谢你的帮助。
答案 0 :(得分:2)
SELECT id, status, photo FROM members WHERE id IN(
SELECT user FROM friendlist WHERE myid = 50624
UNION ALL
SELECT myid FROM friendlist WHERE user = 50624
) AND status = 1
答案 1 :(得分:1)
我的朋友列表:
select
members.*
from friendlist
inner join members
on members.id=friendlist.user
where friendlist.myid=50624 and members.status=1;
与我成为朋友的人
select
members.*
from friendlist
inner join members
on members.id=friendlist.myid
where friendlist.user=50624 and members.status=1;
要合并两个结果,请使用union
select
members.*
from friendlist
inner join members
on members.id=friendlist.user
where friendlist.myid=50624 and members.status=1
union
select
members.*
from friendlist
inner join members
on members.id=friendlist.myid
where friendlist.user=50624 and members.status=1;
答案 2 :(得分:1)
SELECT user AS allfriends
FROM friendlist
INNER JOIN members
ON user = id
WHERE myid = 50624 AND status = 1
UNION
SELECT myid AS allfriends
FROM friendlist
INNER JOIN members
ON user = id
WHERE user = 50624 AND status = 1`
答案 3 :(得分:0)
这样的事情应该有效:
SELECT ALLFRIENDS.id, MEMBERS.status FROM members MEMBERS
JOIN (SELECT id FROM (
SELECT myid AS id FROM friendlist WHERE user=50624
UNION
SELECT user AS id FROM friendlist WHERE myid=50624
) AS tmp
) AS ALLFRIENDS ON ALLFRIENDS.id = MEMBERS.id
WHERE MEMBERS.status = 1;