分组并取得最后一行 [英] Group by and get the last row
问题描述
当我使用
SELECT * FROM报告时WHERE staff ='$ username'GROUP BY taskid
在我的查询中,我得到该组第一行的结果。
我需要添加什么来获得该组最后一行的结果?
最后一行意味着id大于另一行的结果
我尝试添加
ORDER BY id DESC
或
ORDER BY id
但它没有返回预期的结果。
您正在使用不带任何聚合函数的函数组。您可能想通过改为执行一个订单(在查询中没有分组):
SELECT * FROM reports WHERE staff =' $ username'order BY taskid desc;
Group By函数通常用于在特定列上使用聚合函数(如获得平均行值或总和)等。如果您没有使用任何聚合函数,那么使用Group By将不会执行任何操作。
如果您只想从查询中获取一行,则可以添加一个限制子句像这样:
$ p $ SELECT * FROM reports WHERE staff ='$ username'order BY taskid desc limit 1;
When I used the
SELECT * FROM reports WHERE staff='$username' GROUP BY taskid
on my query, I get a result of the first row from that group.
What do I need to add to get the result from the last row of that group?
last row means having id greater than the other row from that group.
I tried adding
ORDER BY id DESC
or
ORDER BY id
but it did not return the intended result.
You are using a group by function without any aggregate functions. You probably want to do an order by instead (No group by in the query):
SELECT * FROM reports WHERE staff='$username' order BY taskid desc;
Group By functions are commonly used when you want to use an aggregate function on a particular column (such as get an average row value, or a sum) and the like. If you are not using any aggregate function, then using Group By will not do anything.
If you only want to get one row from the query you can add a limit clause like this:
SELECT * FROM reports WHERE staff='$username' order BY taskid desc limit 1;
这篇关于分组并取得最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!