How can i combine my two queries?
1:
SELECT `dialog_id` FROM `messages` GROUP BY `dialog_id` HAVING COUNT(*) >= 10 AND MIN(`timestamp`) + INTERVAL 1 HOUR < MAX(`timestamp`)
This query is finding dialogs where more than 10 messages and lasted more than an hour.
2:
SELECT * FROM messages tbl WHERE (SELECT COUNT(*) FROM messages tbl1 WHERE tbl1.dialog_id = tbl.dialog_id AND tbl1.id >= tbl.id AND (user_from = :user_from OR user_to = :user_to)) <= 2 ORDER BY dialog_id DESC
The second query selects two last rows for each dialogs.
So, what i want is select last two rows for each dialogs that lasted more than an hour and where more than 10 messages. I want to show them on the dialog preview page.
Sorry for my english it isn’t my native language.
Advertisement
Answer
You can use window functions for all these calculations:
SELECT m.* FROM (SELECT m.*, ROW_NUMBER() OVER (PARTITION BY dialog_id ORDER BY id DESC) as seqnum, COUNT(*) OVER (PARTITION BY dialog_id) as cnt, MIN(timestamp) OVER (PARTITION BY dialog_id) as min_timestamp, MAX(timestamp) OVER (PARTITION BY dialog_id) as max_timestamp FROM messages m ) m WHERE seqnum <= 2 AND cnt >= 10 AND max_timestamp > min_timestamp + INTERVAL 1 HOUR;