Contagem de posts por mês, ou alfabeticamente em mySQL

Para que situação isso se aplica??

Sistema de blog ou artigos, ou essencialmente qualquer tela semelhante a tela abaixo!

Tela de Artigos

Tela de Artigos

Sem muitas delongas o caminho do pote de ouro:

MES|ANO |TOTAL = “SELECT MONTH(created_at) as mes, YEAR(created_at) as ano, COUNT(*) as total
FROM artigos
GROUP BY MONTH(created_at), YEAR(created_at)
ORDER BY created_at ASC”

LETRA| TOTAL = “SELECT left(titulo, 1) as letra, COUNT(*) as total
FROM artigos
where left(titulo, 1) >= ‘A’ AND left(titulo, 1) <=’Z’
GROUP BY left(titulo, 1)
ORDER BY titulo ASC”

NUMERO| TOTAL =“SELECT left(titulo, 1) as numero, COUNT(*) as total
FROM artigos
where left(titulo, 1) >= ‘0’ AND left(titulo, 1) <=’9′
GROUP BY left(titulo, 1)
ORDER BY titulo ASC”

Minha lógica de impressão foi para mes/ano:

se houve mais de 0 registros na consula faça:

do primeiro registo até o ano atual faça:

de 1 a 12 faça (i):

vai desempilhando os registros caso o mes caso do primeiro registro esteja no topo da lista seja == i

caso nao seja o mesmo mes, nao desempilhe, somente imprima o nome do mes

fim. fim. fim.

Não sei se funciona em outros BDs fora mysql, mas eh provavel que sim. Espero ter sido util!

SQL for Birthday ou Aniversário

This SQL works on MYSQL since 4.0 is for sure, I don’t know about the older versions !

PROBLEM: I want to display people whose birthday today up to 2 days from today! Preferentialy using only DB functions.

SOLUTION: This is way harder than looks like !!!! First because i don’t want to figure a solution that is extremely DB dependent, still i don’t want it slow..

Using BETWEEN tends to go very wrong when we are close to the end of the month, lets say day 30/31 makes the ranges go a little crazy when you use day BETWEEN 30 and 2 ( expect bad results !)

So.. if the simple is the best…

"SELECT * FROM person WHERE
MONTH(birthdate) = MONTH( CURDATE() + INTERVAL 0 DAY ) AND DAY(birthdate) = DAY( CURDATE() + INTERVAL 0 DAY ) OR
MONTH(birthdate) = MONTH( CURDATE() + INTERVAL 1 DAY ) AND DAY(birthdate) = DAY( CURDATE() + INTERVAL 1 DAY ) OR
MONTH(birthdate) = MONTH( CURDATE() + INTERVAL 2 DAY ) AND DAY(birthdate) = DAY( CURDATE() + INTERVAL 2 DAY )"

I use this snippet on my Rails code and it works just fine:

   sql = "SELECT * FROM person WHERE MONTH(birthdate) = ..... "
   ActiveRecord::Base.establish_connection
   @people = ActiveRecord::Base.connection.execute(sql).to_a

*The code is not using a Model for performace issues only.. the query is not supposed to be very heavy, but you could always get the CURRENT month from your App (‘that would mean you are getting the time from the server and not from de DB’)

*Still this is supposed to work on any other programming language… ASP, JAVA, PHP, .NET 😉

Uma consulta/query por data/date

Nada muito interessante mas.. hj tive sérios problemas para pesquisar uma data em um campo que contem date + time

PROBLEMA:

Encontrar todos os logs de 1 dia fornecido pelo cliente em string DD/MM/AAAA em PHP com MySQL

SOLUÇÃO:
$aux2 = explode('/',$date);
$date_form = $aux2[2]."-".$aux2[1]."-".$aux2[0];

blablabla…
“WHERE chatmessage.dtmcreated between ‘$date_form 00:00:01’ and ‘$date_form 23:59:59’ “.
blablabla…

> http://dev.mysql.com/doc/mysql/search.php : uma busca muito pouco funcional com péssimos exemplos práticos..

Espero ter ajudado algum Googler