您好我一直在研究并遇到mysql查询问题 我有一个名为“friends”的表,其中包含列:id,user1和user2。 我正在尝试创建一个查询,我可以获得1条记录,其中包含来自user1列的所有用户和user2列中与特定用户相关的所有用户的串联,以便获得包含所有用户朋友的结果。例如,“朋友”表可能包含:
****friends**** id user1 user2 0 33 1 1 33 2 2 34 25 3 3 33 4 27 33
我想要的结果是名为“friendships”的记录,数据是包含“1,2,3,27”的单个字符串,因为这些是用户33是朋友的所有用户ID。我能跑:
SELECT (CAST(GROUP_CONCAT(user2) AS CHAR(10000) CHARACTER SET utf8)) as friendships from friends where user1 =33
将返回“1,2”并且我可以在单独的查询中将其反转以获得“3,27”,但是,如果可能的话,我试图在一个查询中获得结果!所有的帮助表示赞赏:)
答案 0 :(得分:1)
如果我理解你的问题,我认为这应该有用
select GROUP_CONCAT(a.friendships, b.friendships) as x from ( (SELECT (CAST(GROUP_CONCAT(user2) AS CHAR(10000) CHARACTER SET utf8)) as friendships from friends where user1 = 33) as a, (SELECT (CAST(GROUP_CONCAT(user1) AS CHAR(10000) CHARACTER SET utf8)) as friendships from friends where user2 = 33) as b )
答案 1 :(得分:0)
SELECT
CAST(GROUP_CONCAT(u) AS CHAR(10000) CHARACTER SET utf8) AS friendships
FROM
( SELECT user2 AS u
FROM friends
WHERE user1 = 33
UNION ALL
SELECT user1
FROM friends
WHERE user2 = 33
) AS tmp