I’m having trouble with some MYSQL. The code below has been working fine until a week or two ago when it started grouping anything more recent than 21 Feb 2012 together. The first entry was 18th September 2011 so it hasn’t run for a whole year.
SELECT dept, time, COUNT(*) AS freq
FROM prefix_table1 a
INNER JOIN prefix_table2 b b ON a.author = b.username
GROUP BY WEEKOFYEAR(DATE(FROM_UNIXTIME(time)))
ORDER BY time ASC
LIMIT 24
All I want to achieve with this query is to retrieve the number of entries which have occurred in each week.
Once I have that I process the UNIX stamp in PHP to get the week number in the year and suffix it with the year to allow the stats to work for more than 12 months.
Question is – where have I gone wrong? Why has it stopped working w/c 21st Feb 2012?
The problem is that you’re grouping by a different set of fields than the one you’re selecting. That query has just worked by chance. I mean, you’ve been grouping by WEEKOFYEAR and selecting the time value. What the grouping actually does is “removing” the details and make a group with them applying a function (a count in this case).
Now, you’re trying to show a detail while grouping at the same time, and that results in an incorrect query. For instance, this would work, but won’t show you a detail:
A clear example of the wrong logic of your original query is: If you have grouped, let’s say, 20 records (the count would display 20)… which time would you display for ALL of them if you can only display 1 of those records?
Edit:
As @ypercube said, the previous query might not work depending on if you’re forcing the server to respect ansi standards or not. If that is the case, then you could try running the following (and a little bit unfriendlier) query: