I have a very weird thing to do and simply don’t know how. This is my table and its data:
+------+-----------+-------------+-------+------------+
| uid | entity_id | entity_type | state | created |
+------+-----------+-------------+-------+------------+
| 3913 | 1105 | 1 | 0 | 1340617072 |
| 3913 | 1105 | 1 | 1 | 1340617042 |
| 3913 | 3930 | 1 | 0 | 1340617071 |
| 3913 | 3930 | 1 | 1 | 1340617036 |
+------+-----------+-------------+-------+------------+
created holds the timestamp for which an action has been made, state is the state of the action (followed or unfollowed), uid is who makes the action and entity_id is the entity ID which is being followed/unfollowed.
I’m trying to do a query which gets me all the entity_id which the current user follows. First I was using:
SELECT entity_id FROM follow_objects WHERE uid=? AND entity_type=?
However I noticed that if I follow someone and then unfollow them, I still get a result for that person, because there are 2 entries for it (with state=1 and then state=0).
So I need to get the rows with the newest created column, which means the action is the most recent one. So I’ve tried:
SELECT entity_id FROM follow_objects WHERE uid=? AND entity_type=? group by entity_id HAVING created=MAX(created)
Which returns only rubbish data. I’m out of ideas. Any help?
You need to select on a group-wise maximum. You must wrap the maximum in a subselect and join the table on itself where the
entity_ids are equal and where the subselect’s max timestamp equals the created timestamp. The result is that you’ll get the top row data perentity_idgroup: