我想获取当前用户与之对话的所有用户名和last_messages。
我有两张桌子:
发
用户
所以,如果当前用户的id是1,我应该获得bob和mike的行,但是我得到空的结果。你能帮我找错吗?
SELECT * FROM thread
LEFT JOIN user
ON ((thread.user1_id!=current_user AND thread.user1_id=user.id)
OR (thread.user2_id!=current_user AND thread.user2_id=user.id))
WHERE current_user = 1;
答案 0 :(得分:0)
试试这个:
select
calls.*
from User
left join (
select
User.Name, thread.user2_id as Partner_id
from User join thread on thread.user1_id = user.id
union all
select
User.Name, thread.user1_id as Partner_id
from User join thread on thread.user2_id = user.id
) calls
on calls.partner_id = User.id
where User.id = 1
注意从线程到User的双连接是如何完成的 - 一次将子查询中的调用两侧作为内连接,然后第二次作为外连接的外表。
答案 1 :(得分:0)
请尝试这种方式
SELECT * FROM thread t
LEFT JOIN user u1
ON t.user1_id = u1.id
LEFT JOIN user u2
ON t.user2_id = u2.id
where t.user1_id = '1' or t.user2_id = '1'
应获取bob和mike的行(Thread line 1& 2)