用于创建消息列表的SQL查询

时间:2019-01-01 12:09:03

标签: php mysql laravel

我正在使用Laravel创建消息服务。

我想显示所有基于时间的最新消息。这就是我要实现的This is Im trying to implement

以下是我的表格

  • 消息表
    message table
  • message_user表
    message_user tbale

我尝试了以下代码

SELECT DISTINCT user_id,sender 
FROM ( 
    SELECT DISTINCT message_user.user_id, messages.sender, messages.created_at 
        FROM messages 
        JOIN message_user ON message_user.message_id=messages.id AND message_user.user_id=225
    UNION
    SELECT DISTINCT message_user.user_id, messages.sender, messages.created_at FROM messages 
        JOIN message_user ON message_user.message_id=messages.id AND messages.sender=225 AND message_user.user_id NOT IN (
            SELECT DISTINCT messages.sender 
                FROM messages 
                JOIN message_user ON message_user.message_id=messages.id AND message_user.user_id=225
            )
) mytable 
ORDER BY created_at

问题是输出的格式不正确(未基于created_at排序)

以下是我尝试过的相应Laravel代码

$id        = $request->user()->id;
$user      = User::find($id);
$buddylist = $user->messages()->select(DB::raw('message_user.user_id,messages.sender,messages.created_at'));
$subquery  = Message::select(DB::raw(' messages.sender'))->join('message_user','messages.id','=','message_user.message_id') ->where("message_user.user_id",'=',$request->user()->id);
$mybuddy   = Message::selectRaw('message_user.user_id,messages.sender,messages.created_at')
          ->join('message_user','messages.id','=','message_user.message_id')
          ->where("messages.sender",'=',$request->user()->id)
          ->whereNotIn('message_user.user_id', $subquery)
          ->union( $buddylist)
          ->groupBy('sender')
          ->groupBy('user_id')
          ->orderBy('created_at','desc')
          ->get();

1 个答案:

答案 0 :(得分:2)

如果您还有另一列名为“ receiver_id”的列,您可以做的是:

$query="select * from messages WHERE sender_id='user_id' or receiver_id='user_id' ORDER BY created_at asc";