Please consider the following table structure (this is sample data, so please ignore the timestamps being identical):
+---------+---------+------------+-----------+
| list_id | item_id | date_added | is_active |
+---------+---------+------------+-----------+
| 1 | 1 | 1352073600 | 1 |
| 1 | 2 | 1372073600 | 1 |
| 1 | 3 | 1332073600 | 1 |
| 1 | 4 | 1302073600 | 1 |
| 2 | 1 | 1302073600 | 1 |
| 3 | 1 | 1302073600 | 1 |
+---------+---------+------------+-----------+
Our client wishes to show how many lists were created on a certain day. The list is created when the first item is added, but the date is not explicitly stored, only the date the items have been added.
My question is this:
Using MySQL (and PHP for computing the timestamp), how can I return the number of lists that were created on a certain day. Essentially, the logic should be (pseudo-code):
- select total records from
tbl_list_itemswheredate_added>= min_age anddate_added<= max_age, and record is oldest for this list
It is difficult to explain what I’m looking for, so consider the following actions:
No items added to lists yet (i.e. all lists have 0 items)
User added `item_id = 1` to `list_id = 1` yesterday.
User added `item_id = 2` to `list_id = 1` today.
User added `item_id = 1` to `list_id = 2` yesterday.
User added `item_id = 1` to `list_id = 3` yesterday.
User added `item_id = 2` to `list_id = 2` today.
If we wanted to look how many lists were created yesterday (or rather, how many lists had the first item added yesterday), I would like to return the total number where the item first added = yesterday. Given the action set above, this would return a total of 3 (i.e. list_id = 1, list_id = 2 and list_id = 3).
This returns the list of lists created on a specific day:
To count them you can count number of results of the query, or use sub-queries like:
However, note that this is totally not-optimized, because you have to GROUP BY the whole table for each query; maybe will be better to add a flag ( creation = 0 | 1 ) when the first item of a list is added.