I want to get the number of comments that are at least one hour apart. I wrote this query and it works fine.
SELECT COUNT(`c`.`id`) `count`
FROM `comments` `c`
WHERE `user_id` = '28' AND (TIMESTAMPDIFF(SECOND, (
SELECT MAX(`created_at`)
FROM `comments`
WHERE `user_id` = '28' AND `created_at` < `c`.`created_at`
), `c`.`created_at`) > 3600 OR TIMESTAMPDIFF(SECOND, (
SELECT MAX(`created_at`)
FROM `comments`
WHERE `user_id` = '28' AND `created_at` < `c`.`created_at`
), `c`.`created_at`) IS NULL)
But as you can see, this statement is repeated two times:
SELECT MAX(`created_at`)
FROM `comments`
WHERE `user_id` = '28' AND `created_at` < `c`.`created_at`
How can I write it cleaner?