我正在使用laravel framework 5.3。执行查询后,我得到了错误的结果。我有两个表,一个是用户,另一个是message.Here是我的场景
enter code here
User table-
id name
1 a
2 b
3 c
Message table:
id sender_id receiver_id message
1 1 2 hii
2 2 1 hello
3 1 3 hiiii
现在我想获取具有sender_id和receiver_id的用户之间的最后一条消息 这是我的代码: -
enter code here
$coreQueryUser=DB::select(
'
select m.* ,u.*
from
messages m
inner join (
select max(id) as maxid
from messages
where messages.sender_id = 1 // here i am sending userid is 1
group By (if(sender_id > receiver_id, sender_id, receiver_id)),
(if(sender_id > receiver_id, receiver_id, sender_id))
) t1 on m.id=t1.maxid
join
users u ON u.id = (CASE WHEN m.sender_id = 1
THEN m.sender_id
ELSE m.receiver_id
END)
'
);
注意 - 我想查找与userid(1)一起使用的所有最后消息 在此先感谢:)
答案 0 :(得分:0)
使用ORDER BY
词组,并使用LIMIT
将结果限制为 1 。
我的回答是假设id
行是主键,并且自动递增
修改代码\
enter code here
$coreQueryUser=DB::select(
'
select m.* ,u.*
from
messages m
inner join (
select max(id) as maxid
from messages
where messages.sender_id = 1 // here i am sending userid is 1
group By (if(sender_id > receiver_id, sender_id, receiver_id)),
(if(sender_id > receiver_id, receiver_id, sender_id))
) t1 on m.id=t1.maxid
join
users u ON u.id = (CASE WHEN m.sender_id = 1
THEN m.sender_id
ELSE m.receiver_id
END)
ORDER BY m.id DESC LIMIT 1
'
);