简体   繁体   English

同一张桌子上有多个JOIN

[英]Multiple JOIN on the same table

I'm working on a messaging system on Laravel and I have the following tables : 我正在Laravel上的消息传递系统上工作,并且具有以下表格:

USER 用户

user_id | email | password | name | ...
---------------------------------------

CHAT 聊天

chat_id | user1_id | user2_id
-----------------------------

MESSAGE 信息

message_id | content | date | user_id | chat_id | ...
------------------------------------------------------

and what I want to do, is to get all the chats the authenticated user have started with an other one, ordered by the date of the messages (from the most recent to the oldest one), plus the information on the user he's talking to. 我想做的是让经过身份验证的用户与其他人开始所有聊天,并按消息的日期(从最新到最早的)排序,再加上与之交谈的用户的信息。

I'm currently working on the raw SQL request before passing it in Laravel and this it what I try but it doesn't give the waited result : 我目前正在处理原始SQL请求,然后再将其传递给Laravel,这是我尝试的方法,但它没有给出等待的结果:

SELECT user.user_id, user.name, user.surname
FROM user
JOIN chat a
ON user.user_id = a.user1_id
JOIN chat b
ON user.user_id = b.user2_id
WHERE b.chat_id IN
    (SELECT chat_id 
     FROM chat 
     WHERE user1_id = 1 OR user2_id = 1) 
AND user.user_id != 1  

----> (I'm testing with the user that has the ID #1)

If anyone could help that would be greatly appreciated. 如果有人可以帮助,将不胜感激。

You can use Union to get both results as follows: 您可以使用Union来获得两个结果,如下所示:

select a.user1_id, a.chat_id, user.fname, user.lname 
from user
join chat a on a.user2_id = user.user_id and a.user1_id = 1
union 
select b.user2_id, b.chat_id, user.fname, user.lname 
from user
join chat b on b.user1_id = user.user_id and user2_id = 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM