Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL count only new records

How to write a MySQL query to achieve this task?

Table: writers

w_id    w_name
---------------
  1     Michael
  2     Samantha
  3     John
---------------

Table: articles

a_id   w_id   timestamp   a_name
----------------------------------------
  1      1        1       PHP programming
  2      3        3       Other programming languages
  3      3        5       Another article
  4      2       15       Web design
  5      1       20       MySQL
----------------------------------------

Need to COUNT only those writers who published their first article not earlier than 5.
(only writers who published at least one article can be counted)


In this example the result would be: 1 (one writer - Samantha)

SQL code can be tested in this SQLFiddle

like image 811
acoder Avatar asked Dec 12 '22 22:12

acoder


1 Answers

You need a double SELECT.

First you fetch w_id, together with timestamp of first article:

SELECT w_id, MIN(timestamp) as publish FROM articles GROUP BY w_id

Then you request that publish is not earlier than 5:

SELECT w_id, MIN(timestamp) as publish
    FROM articles
    GROUP BY w_id
    HAVING publish >= 5;

Then you join that "table" with writers to get the name, if you want.

But if you only want the count, you do not need the writers table at all:

    SELECT COUNT(*) AS answer FROM
    ( SELECT w_id, MIN(timestamp) AS publish
        FROM articles
        GROUP BY w_id
        HAVING publish >= 5
) AS counter;

Test: http://sqlfiddle.com/#!2/0e90f/30/0

like image 63
LSerni Avatar answered Dec 30 '22 12:12

LSerni