简体   繁体   中英

mysql queries in order -> limit,sort,group. How?

oh, that's driving me crazy. I have messages table, simplified example:

id[int] - sender[int] - receiver[int] - conv_id[bigint] - received[int] - stamp[int]
   1          2             1               5                  1          timestamp+1 
   2          2             1               5                  1          timestamp+2
   3          3             1               6                  1          timestamp+3 
   4          4             1               7                  1          timestamp+4
   5          5             1               8                  1          timestamp+5 
   6          5             1               8                  1          timestamp+6

now I'm interesting a results grouped by receiver, limited to 3 senders and sorted by stamp DESC. How to do that?

I already have this, but it's taking all messages and i believe that's not the best way to not loose performance, even though I'm really not the guru of mysql:

SELECT id, sender, receiver, conv_id FROM
   (SELECT m.id, m.sender, m.receiver,m.conv_id 
    FROM messages AS m WHERE m.receiver = 1 AND m.received = 1 
    ORDER BY m.stamp DESC) as messages_tmp 
WHERE receiver = 1 GROUP BY conv_id ORDER BY NULL LIMIT 0,3

This should return these results in that order:

id = 6, id = 4, id = 3

The thing is I'm already doing to queries of this, for m.received = 0 and than if not enough of the results, for m.received = 1 . So far my database isn't too big, but if it's gets bigger I'm afraid it can be slow. I'm thinking about possibility to limit results of the subquery, but have no idea how to that and be sure I'll get enough results after GROUP. Thanks.

SELECT id, sender, receiver,conv_id 
FROM messages WHERE receiver = 1 AND received = 1 
GROUP BY conv_id
ORDER BY id DESC LIMIT 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM