Count records only if greater than the current datetime, with count ()

2

I have the following query :

SELECT u.nome, u.email, u.login, u.data_cadastro, COUNT(*) AS qtd
FROM patrocinadores AS p
   LEFT JOIN anuncios AS a ON a.id_user = p.id_user
   INNER JOIN usuarios AS u ON u.id = p.id_user
WHERE p.id_patrocinador = '1' GROUP BY a.id_user

It pulls all the registrations that were sponsored by the ID 1 . And also returns me how many ads each sponsored domain has.

This command works perfectly, but I only need to pull the number of active ads, that is, only when the expira > time() column.

When I leave the query thus, with WHERE a.expira > '...' ,

SELECT u.nome, u.email, u.login, u.data_cadastro, COUNT(*) AS qtd
FROM patrocinadores AS p
   LEFT JOIN anuncios AS a ON a.id_user = p.id_user
   INNER JOIN usuarios AS u ON u.id = p.id_user
WHERE p.id_patrocinador = '1' AND a.expira > '1449365367' GROUP BY a.id_user

It only returns me the records where a.expira is greater than the current time. I want it to return all, but if the column time is less than the current time then it counts as 0 that record.

I just want to make a system that counts how many ads the accounts that are sponsor 1 have assets.

    
asked by anonymous 05.12.2015 / 02:39

1 answer

2

I would suggest using this:

SUM( IF( a.expira > 1449365367, 1, 0 ) )

Explanation:

The SUM is used to sum the values of a field, and based on this we create a special "field" that will give us 1 for all the cases we want to count, and zero for those that do not.

The function IF drops like a glove in this case, because it will return 1 if a.expira > 1449365367 , otherwise, zero. The syntax of the IF function is this:

IF( condição, resultado se positivo, resultado se negativo)
    
05.12.2015 / 04:23