Highest entry from group by and compare to another value using having

72 Views Asked by At

This is what I want:

Look if the highest created from the same FK is more than X days old.

This is how the data is structured (this is not the result from the query below):

table_1

id     |      FK_table_2      |     created
-------------------------------------------------------
1      |      20              |     2013-11-12 12:13:14
2      |      20              |     2013-11-12 11:10:12
3      |      21              |     2013-10-02 12:53:20
4      |      21              |     2013-09-02 12:54:20

Note: Doing a subquery will be to slow.

What I come up with is:

SELECT *
FROM table_1
GROUP BY FK_table_2
HAVING MAX(created) < NOW() - INTERVAL 3 DAY

I'm worried that HAVING MAX(created) has not garantuee to use the highest created.

Is there any other ways to do this?

2

There are 2 best solutions below

1
On

I don't think you need to use a MAX clause, you can surely just select all rows older than 3 days and do your work on them.

SELECT DISTINCT FK_table_2 FROM table_1
WHERE created > NOW() - INTERVAL 3 DAY;

Update this won't work :-(

5
On

try this

SELECT FK_table_2,max(created)
FROM table_1
where created < NOW() - INTERVAL 3 DAY
GROUP BY FK_table_2