4
I would like to know how I can query the Mysql database and group the records by year and month.
At the moment I first make a query to get the year records, then for each year I use a for() to filter the results per month within that year. For example:
$ano = sql("SELECT DISTINCT YEAR(dataCadastro) as 'ano' FROM tabela");
foreach ($ano as &$row) {
$ano = $row['ano'];
for ($i=1; $i<=12; $i++) {
$item = sql("SELECT id, ... FROM tabela WHERE YEAR(dataCadastro) = '$ano' AND MONTH(dataCadastro) = '$i'");
$row[$i] = $item;
}
}
Researching on the subject I saw that I could use GROUP BY
, but when I try to use it, the query returns empty, even though I’m sure it would have results. For example:
$grupo = sql("SELECT id, ... FROM tabela"); //Retorna os dados corretamente
$grupo = sql("SELECT id, ... FROM tabela GROUP BY YEAR(dataCadastro)"); //Retorna vazio
The date in the database is like datetime
, ex.: 2016-11-09 17:30:00
Is there any way to get this result using the GROUP BY
? Because from the research I’ve done, I’ve observed that yes, but when I try to execute, I can’t get the results.
Remembering that the first way I showed (with the use of foreach
) I can get the results as I wish, but I would like to simplify the process.
When you use the
group by
tried to run this query directly in the database? which version of Mysql vc uses?– rray
@rray according to Wamp, this is the version: 5.7.14. When I run straight into the bank it also has an error, this is it:
SELECT list is not in GROUP BY clause and contains nonaggregated column 'id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
– celsomtrindade
You are using PDO?
– novic
@Virgilionovic yes.
– celsomtrindade
@Celsomtrindade has a way of doing that the key would be the same, like
["012016"] => [[],[],[]]
records would be separated by month and year within a key, it is more or less than needed?– novic
@Virgilionovic if I understand correctly, yes. It would be to assemble a report, so I need to separate by year and month, where each month contains an array of records corresponding to that month. As I did in the first code example, I get this result, including generating an empty array if there are no records in that month.
– celsomtrindade
Then you gave me extra information, the way I was going to give you would not be able to generate what is missing only what is on the table!
– novic
So this must be it, the
group by
Mysql is not ansi or in most of the fields you are obliged to group by all columns that are in select, this became valid in Mysql5.7.5 see in document, I believe that that be the problem. As a test try to group by all question columns in select.– rray