Tengo un sistema de chat y quiero mostrar los mensajes enviados en la última hora, pero también quiero mostrar los últimos 20 mensajes sin importar cuánto tiempo hace que se enviaron.
¿Hay alguna manera de que pueda hacer esto en una consulta SQL?
CREATE TABLE IF NOT EXISTS `chat` ( `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT, `user_id` INT(11) UNSIGNED NOT NULL, `item_id` INT(11) UNSIGNED NOT NULL, `message` TEXT NOT NULL, `recipient` INT(11) NOT NULL DEFAULT '0', `type` ENUM ('message', 'announcement') NOT NULL DEFAULT 'message', `channel` ENUM ('general', 'private') NOT NULL DEFAULT 'general', `posted` DATETIME NOT NULL, PRIMARY KEY (`id`), KEY `user_id` (`user_id`), KEY `posted` (`posted`), KEY `type` (`type`), KEY `channel` (`channel`), KEY `recipient` (`recipient`) ) ENGINE = MyISAM DEFAULT CHARSET = `utf8` AUTO_INCREMENT = 2;Esto debería funcionar:
( select * from chat where timestamp > DATE_SUB(now(), interval 1 hour) ) union ( select * from chat order by posted desc limit 20 ) order by postedExplicación:
Entonces, cuando no haya datos en la última hora, aún obtendrá las 20 publicaciones más recientes. Si hay muchos datos en la última hora, los obtendrá todos.
Prueba esto:
SELECT * FROM `chat` ORDER BY `posted` DESC LIMIT 0,20;Enumerará las últimas 20 filas (por fecha/hora). Dado que desea chats más antiguos cuando no hay suficientes en la última hora, no necesita preocuparse por la antigüedad de los chats.
Lo siguiente no se ha probado y puede tener un error de sintaxis, por lo que es posible que tenga que jugar un poco con él.
SELECT * FROM `chat` WHERE DATE_ADD(a.`posted` interval 1 hour) <= NOW() UNION ( SELECT * FROM `chat` WHERE a.posted > DATE_SUB(NOW(), interval 1 hour) AND (SELECT count(*) FROM `chat` WHERE a.posted <= DATE_SUB(NOW(), interval 1 hour)) < 20 ORDER BY `posted` DESC LIMIT 0,20) ORDER BY `posted` DESCSolo debe agregar las publicaciones anteriores a la última hora cuando hay menos de 20 publicaciones en la última hora.