I have a user feed of image posts. Each user can post single images, however, he can repeat the action often. Say, upload several images within an hour.
How do I effectively design the database table so when a user posts multiple images (one by one) within one hour — I can easily group those serial posts together, eigher on INSERT or on SELECT?
Don’t suggest multi-upload form. That’s not the case: I’ve just described the task in more common terms 🙂
That’s out playground:
We’d like to group together posts that are temporally close.
First, declare the wanted granularity: the threshold to temporal proximity:
Each row forms a group with group ID matching the row id (it can also be a timestamp):
Each group contains rows that originate from the same user, were posted earlier than the group-former:
Each row belongs to multiple groups. For each row, we pick the most ‘broad’ group: it has the biggest rowId
The most recently updated group always jumps to the top (if you sort by
groupDESC).However, if you’d like the groups be persistent (e.g. so items don’t move from one group to another), use
MINinstead ofMAX:Now, we’re going to update the table’s
groupcolumn.First, MySQL can’t update the same table you’re reading from. Wee need a temporary table.
Second: we only update the rows whose
groupcolumn is NULL, or rows posted later thanUNIX_TIMESTAMP()-2*@threshold:And update the
groupcolumn:Here’s the SQLFiddle: http://sqlfiddle.com/#!2/be9ce/15