将 ORDER BY 与已有 GROUP BY 的查询一起使用
我正在使用 MySQL,并且我有一个表,其中有一列包含日期(我正在制作一个课程的截止日期表)。以前我的查询如下:
SELECT * FROM duedates_f2011 ORDER BY anothercolumn
为了防止重复出现(基于截止日期列),我必须将其更改如下:
SELECT * FROM duedates_f2011 GROUP BY duedate
目前,它保留相同的顺序,但如何确保它仍然会这样做?我读过的 GROUP BY 教程中没有任何内容表明它仍然会对它进行排序,并且随后添加 ORDER BY 语句是不正确的。是否有我遗漏的东西,或者我应该添加其他东西以确保它保持秩序?
(如我的标签所示,我正在使用 PHP 来运行查询)
I'm using MySQL and I have a table that has dates in a column (I'm making a table of due dates for a class). Previously I had the query as follows:
SELECT * FROM duedates_f2011 ORDER BY anothercolumn
In order to prevent duplicate occurrences (based on the duedate column) I had to change it as follows:
SELECT * FROM duedates_f2011 GROUP BY duedate
Currently, it's retained the same order, but how can I assure that it will still do so? Nothing in the GROUP BY
tutorials I've read indicates that it will still sort it, and adding an ORDER BY
statement afterwards is incorrect. Is there something I'm missing, or is there something else I should add to make sure it remains in order?
(as indicated in my tags, I'm using PHP to run the query)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是根据 MySQL 手册页。
This is according to the MySQL manpages.
先分组选择,然后再排序怎么样?
我认为您没有任何理由决定按分组列对其进行排序。 大胆!对数据库的要求更高!它应该屈服于你的每一个突发奇想!
How about selecting with a grouping first, then doing the order later, like this?
I don't see any reason for you to settle on it being ordered by the grouped column. Be bold! Demand more of your database! It should bow to your every whim!
您可以使用
group by ... order by ...
(按此顺序)。如果您仅使用group by
,它将按该列自动排序。但是,如果您想要
按到期日期分组
和按另一个列排序
,请意识到一件事:当您按到期日期分组时,sql 不知道要为另一个列取哪个值...编辑:来自mysql手册< /a>
You can use
group by ... order by ...
(in this order). If you use justgroup by
, it will be ordered automatically by that column(s).However, if you want to
group by duedate
andorder by anothercolumn
, realize one thing: the sql doesn't know which value to take for anothercolumn, when you group by duedate...edit: from the mysql manual