So I’m running a query against a MariaDB in PHPMyAdmin, its been working fine until we have got to a new month and for the life of me I can’t see the issue. The table is in the following format as an example, it contains data for both July and August so far:
timestamp | generation | export |
---|---|---|
2023-08-01 23:00:00 | 43.4 | 12.5 |
The SQL that’s working for for returning the MAX value for month 7 and year 2023;
$sql_a = "SELECT DATE_FORMAT(`timestamp`, '%a %d %M') AS timestamp, `generation` FROM solar_generation WHERE `generation` = (SELECT MAX(`generation`) FROM solar_generation) AND MONTH(timestamp)= 7 AND YEAR(timestamp) = 2023";
This outputs exactly what I expect:
Fri 07 July 43.0
If I change the SQL to month number 8
SELECT DATE_FORMAT(`timestamp`, '%a %d %M') AS timestamp, `generation` FROM solar_generation WHERE `generation` = (SELECT MAX(`generation`) FROM solar_generation) AND MONTH(timestamp)= 8 AND YEAR(timestamp) = 2023;
I get the following despite there been data in the table;
MySQL returned an empty result set (i.e. zero rows)
If run the following query:
SELECT MAX(`generation`) FROM solar_generation WHERE MONTH(timestamp)= 8 AND YEAR(timestamp) = 2023;
I get the MAX generation as I’d expect for August, as soon as I start building the query for getting the data it stops returning data?
What is it I’m doing wrong, I just assumed the same query would work or is there a flaw in the query that is exposed by month 8 ?
2
Answers
I don’t use MariaDB.
However, this looks suspicious:
Basically, it says:
solar_generation
generation
column value is equal to the largestgeneration
value in the whole tablegeneration
column valuegeneration
value doesn’t belong to August (2023)This is Oracle, but disregard that fact; it is just to illustrate what I think is going on:
Now, let’s select all rows that satisfy conditions: max generation and July:
What about max generation and August?
Right; there are no rows because
generation = 99
belongs to July.I don’t know what result you expect as you didn’t explain it; if it is about max generation per month, then you’d do something like this (Oracle again; adjust it to MariaDB syntax):
The answer provided by Littlefoot shows exactly where the problem is.
The max value doesn’t belong to the August month.
You need to make a little change to your logic . Find the max value per specific month and year.
In your case it would be ,
I suggest using with clause at is more performant and easily to adapt if future changes happen,
See example