I have a table with items that are part of a thread, so they have a thread ID, each item also has a date (UNIX timestamp). So my table looks something like (UNIX timestamps simplified):
+-----------------------------+
| id | date | thread_id |
+-----+---------+-------------+
| 1 | 1111 | 4 |
| 2 | 1333 | 4 |
| 3 | 1444 | 5 |
| 4 | 1666 | 5 |
+-----------------------------+
What I want to do is select thread IDs where ALL the items sharing the same thread ID are smaller than the passed date. So if I wanted thread IDs where ALL items are older than 1555 (date < 1555), I would only expect to have thread ID 4 returned, not 5 even though it's got an item with a date smaller than 1555. So this is what I tried:
SELECT * FROM table WHERE date < 1555 GROUP BY thread_id ORDER BY date DESC
What I'm trying to do with that query is group all items by thread ID around the item with the highest date value and from there get the items where the date is less than 1555. But that doesn't work, it will still return thread ID 5 because it's got an item older than 1555.
So to summarize, how would I only select thread IDs where ALL items are older than a certain date?
Thank you for your time!
GROUP BY clause is used with the SELECT statement. In the query, GROUP BY clause is placed after the WHERE clause.
Important points for the GROUP BY SQL Statement: The GROUP BY statement can only be used in a SQL SELECT statement. The GROUP BY statement must be after the WHERE clause. (If one exists.) The GROUP BY statement must be before the ORDER BY clause.
The GROUP BY clause is placed after the WHERE clause. The GROUP BY clause is placed before the ORDER BY clause.
The WHERE clause is applied before the GROUP BY clause. It filters non-aggregated rows before the rows are grouped together. To filter grouped rows based on aggregate values, use the HAVING clause. The HAVING clause takes any expression and evaluates it as a boolean, just like the WHERE clause.
SELECT thread_id FROM table GROUP BY thread_id HAVING MAX(date) < 1555
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With