不幸的是,您正在查看的帖子是错误的。 MySQL文档明确指出group by
在group by
子句中没有指定时为列选择任意值。
以下是来自here的明确引用。
MySQL extends the use of GROUP BY so that the select list can refer to nonaggregated columns not named in the GROUP BY clause. This means that the preceding query is legal in MySQL. You can use this feature to get better performance by avoiding unnecessary column sorting and grouping. However, this is useful primarily when all values in each nonaggregated column not named in the GROUP BY are the same for each group. The server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate. Furthermore, the selection of values from each group cannot be influenced by adding an ORDER BY clause. Sorting of the result set occurs after values have been chosen, and ORDER BY does not affect which values within each group the server chooses.
正确的做法(这是标准SQL)是计算适当的最大时间戳记,然后加入结果回:
SELECT t.*
FROM table_name t join
(select name, year, category, max(timestamp) as maxts
from table_name
WHERE year ='2013' AND category='Network'
group by name, year, category
) tn
on t.name = tn.name and
t.year = tn.year and t.category = tn.category and t.timestamp = tn.maxts
ORDER BY sales_total DESC;
编辑:
这是您的查询:
SELECT t.*
FROM annualtable t join
(SELECT year, name, max(countries)
FROM annualtable
WHERE name NOT LIKE '%No Entries%' and year <> '0'
GROUP BY year
ORDER BY year
) tn
on t.name = tn.name and t.year = tn.year t.countries = tn.countries
ORDER BY year DESC;
有两个问题。其中一个是在on
的第三个条款之前缺少的and
。第二个是你需要在子查询的group by
中包含name
。如果您希望order by
做任何事情,您可能会遇到其他问题。请参阅文档中的上述参考。所以,你可能想要这个:
SELECT t.*
FROM annualtable t join
(SELECT year, name, max(countries)
FROM annualtable
WHERE name NOT LIKE '%No Entries%' and year <> '0'
GROUP BY year, name
) tn
on t.name = tn.name and t.year = tn.year and t.countries = tn.countries
ORDER BY year DESC;
你能告诉我们你的PHP代码吗? –
显示您的php代码 –
“查询失败”确实是完整的完整错误信息? –