Try this query
select
*
from
(select
@rn:=if(@prv=receiver, @rn+1, 1) as rId,
@prv:=receiver as receiver,
chat_id,
sender,
msg,
msg_time
from
tbl
join
(select @rn:=0, @prv:='')tmp
order by
receiver, msg_time desc)tmp
where rid >= 20;
This select query will return all the records other than last 20 for each user, you can use it accordingly in your delete statement..
delete
a
from
tbl a
inner join
(select
@rn:=if(@prv=receiver, @rn+1, 1) as rId,
@prv:=receiver as receiver,
chat_id,
sender,
msg,
msg_time
from
tbl
join
(select @rn:=0, @prv:='')tmp
order by
receiver, msg_time desc
)tmp
on
a.chat_id=tmp.chat_id
where
tmp.rId >20