如何在mysql中为每个用户获取最新消息?

时间:2020-09-07 13:03:24

标签: mysql sql datetime greatest-n-per-group window-functions

我有数据库来存储客户和消息

enter image description here

我正在尝试获取所有客户及其最新消息的列表,例如Messenger中的第一个屏幕。

<%= form_for @bill do |f| %>
    <% if @allItems %>
        <% @allItems.each_with_index do |item, index| %>
            <%= f.fields_for :bill_items do |s| %>
                <tr class="table-success" scope="col-8">
                    <td class="text-primary"><%= s.label item.name %></td>
                    <td><%= check_box_tag "bill[bill_items_attributes][#{index}][item_id]", item.id, false, class: 'selectable' %> </td> 
                    <td><%= s.number_field(:quantity, in: 1.0..100.0, step: 1) %></td>
                    <td><%= s.label  :price, item.price %></td>
                </tr>
            <% end %>
        <% end %>
    <% end %>
   
    <div class="form-group row justify-content-center">
        <%= f.submit "Create Order with Selected items", class: "btn btn-secondary" %>
    </div>
<% end %>

但是这将返回所有用户的所有消息。我也尝试过这样做

SELECT *
FROM message AS m
LEFT JOIN customer AS c ON c.id=m.sender_id
ORDER BY m.sent_at DESC

但这不能在所有数据库上运行,并且不能对结果集进行排序以仅获取最新消息。

1 个答案:

答案 0 :(得分:5)

一个选项使用row_number(),在MySQL 8.0中可用:

select *    -- better enumerate the columns you want here
from customer as c
left join (
    select m.*, row_number() over(partition by m.sender_id order by sent_at desc) rn
    from messages m
) m on on c.id = m.sender_id and m.rn = 1
order by m.sent_at desc

这为您提供了每个客户的最新消息。如果您想要更多消息,可以在rn上更改条件(rn <= 3会给每个客户3条消息。)

请注意,我更改了left join中表的顺序,因此它允许没有消息的客户(而不是没有客户的消息,这可能没有意义)。

如果您运行的是早期版本,则可以使用子查询进行过滤:

select *    -- better enumerate the columns you want here
from customer as c
left join messages m 
    on  m.sender_id = c.id
    and sent_at = (select min(m1.sent_at) from messages m1 where m1.sender_id = m.sender_id)

要获得相关子查询的性能,请考虑在(sender_id, sent_at)上建立索引(理想情况下,这些列中不应有重复项)。

相关问题