Mysql - Select the most inserted records in a given period

Asked

Viewed 28 times

0

I am needing to select all most recurring records (top 5) within a time interval but am not getting.

Basically when I do this:

SELECT assunto, count(*) AS total 
 FROM tabMsgs 
WHERE dtCriacao > '2021-05-08' AND dtCriacao < '2021-05-16' GROUP BY assunto 
ORDER BY total DESC LIMIT 5;

I get the count of records, grouped by subject in descending order limited to 5... Great, but now that I know who are the top 5 subjects with more count of records and their respective amount I want to select all these records.

I’m doing so unsuccessfully:

SELECT id, assunto, dtCriacao 
  FROM tabMsgs A 
 WHERE dtCriacao > '2021-05-08' 
   AND dtCriacao < '2021-05-16' 
   AND assunto = (SELECT max(assunto) from tabMsgs B WHERE B.assunto = A.assunto);

This query is returning all records in this time interval, but I need you to return all records of the 5 subjects with the highest amount of records.

I don’t know if I’ve made myself clear.

  • put example of data in the question. About queries, in the second you can use BETWEEN in the date, and subquery Select the 5 subjects you want and use AND assunto in ( that may be enough, but without seeing the data it is difficult to say more

1 answer

0


You can use a INNER JOIN with that sub-query, something like that:

SELECT
    a.id, a.assunto, a.dtCriacao
FROM
    tabMsgs
INNER JOIN (
    SELECT
        assunto, count(*) AS total
    FROM
        tabMsgs
    WHERE
        dtCriacao > '2021-05-08' AND
        dtCriacao < '2021-05-16'
    GROUP BY
        assunto
    ORDER BY
        total DESC
    LIMIT
        5
) b ON
    a.`assunto` = b.`assunto`
WHERE
    a.dtCriacao > '2021-05-08' AND
    a.dtCriacao < '2021-05-16' 
  • can use the BETWEEN to filter the dates but, it is necessary to filter twice, since the subquery already does this?

  • @Ricardopunctual, it is necessary to search twice for all records that have the same subject as those located in the subquery, then return from all dates. I didn’t put BTWEEN to show that what he was already doing wasn’t so far from finding the solution.

  • Thank you guys, the reply from @Robertodecampos went perfectly, thank you very much for the help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.