Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

191
Views
Obtenga registros de la última hora o de los últimos 20 elementos si no hay ninguno en la última hora

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;
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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 posted

Explicación:

  • Selecciona todos los mensajes de la última hora.
  • También selecciona los últimos 20 mensajes, como una consulta separada (20 registros es rápido)
  • La unión fusiona los dos resultados y elimina los dobles en caso de que haya superposición entre los dos.

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.

over 4 years ago · Santiago Trujillo Report

0

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` DESC

Solo debe agregar las publicaciones anteriores a la última hora cuando hay menos de 20 publicaciones en la última hora.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!