我有用户表 有 id 字段 友情表 frienduser 有 friend1id 或 friend2id 根据谁先向谁发送请求 并喜欢表| thread_id - 用户ID 我希望从用户那里选择我的朋友,并喜欢这个话题的人
答案 0 :(得分:2)
丑陋的部分是 frienduser 表可以在任一ID上链接。我认为解决这个问题的最简单方法是使用工会。
/* Case 1: My ID is friend1id, my friend is friend2id */
select u2.*
from users u1
inner join frienduser f
on u1.id = f.friend1id
inner join users u2
on f.friend2id = u2.id
inner join likes l
on u2.id = l.userid
where u1.id = @MyUserId
and l.threadid = @MyThreadId
union
/* Case 2: My ID is friend2id, my friend is friend1id */
select u2.*
from users u1
inner join frienduser f
on u1.id = f.friend2id
inner join users u2
on f.friend1id = u2.id
inner join likes l
on u2.id = l.userid
where u1.id = @MyUserId
and l.threadid = @MyThreadId
答案 1 :(得分:1)