echo "<div class=messagess>";
$msg=$db->query("SELECT * FROM `messages` WHERE `recipient`='{$_SESSION['id']}'");
while($r=mysqli_fetch_array($msg)){
$users=$db->query("SELECT * FROM `users` WHERE `id`='{$r['author']}'");
while($r2=mysqli_fetch_array($users)){
$avatar=select('background', 'avatar', 'id', $r['author'], true);
$style = '';
if($r2['level'] != 'Пользователь'){
$style='mm';
}
echo "<a href=/messages?type=private&id=".$r2['id'].">";
echo "<div class=user>";
echo "<img class='ava $style' src=".photo($avatar[0])."><br>";
echo "<b><h2 class=nick>".$r2['nickname']."</h2></b>";
echo '<span class=ms>'.mb_substr($r['message'], 0, 30).'</span>';
echo "</div>";
echo '</a>';
select a.*
from (select m.*, u.*, count(select *
from messages as m2
join users as u2 on u2.id = m2.author
where m2.recipient = 1
and u2.id = u.id -- имитация клаузы partition by
and m2.id > m.id -- имитация клаузы order by ... desc
) as row_num, -- аналог row_number через оконную функцию:
-- row_number() over(partition by u.id order by m.id desc) as row_num
from messages as m
join users as u on u.id = m.author
where m.recipient = 1
) as a
where a.row_num = 1 -- берем 1 строку по ранжированному счетчику в пределах каждого id пользователя