0

Lets say I have a table - tasks - with the following data:

task    user     when_added
---------------------------
run     1        2012-08-09
walk    2        2012-08-07
bike    2        2012-08-07
car     1        2012-08-06
run     2        2012-08-06
car     1        2012-08-05
bike    1        2012-08-04
run     1        2012-08-04

As you can see the task is repetitive.

Question is, when i show the data e.g.

select * from tasks group by task order by when_added desc

How does the group by affecting the results? Does 'group by' group them in any order, can I make it?

The reason i ask is that I have a large table which i show data as above and if I lose the group by and just show results in date order, I get some results which do not show on group by, which means the task has been done before but it seems to be grouping by the oldest date and i want the newest date at the top of the pile.

Hope this makes sense...is it possible to affect the group by order?

4

1 に答える 1

1

それはあなたが望むものですか?

select task, group_concat(user), max(when_added)
from tasks 
group by task
order by when_added desc

group by集計関数です。MySQL では、いずれにせよ集計列を選択できませんが、それを行うべきではありません。

列ごとにグループ化すると、その列の結果が明確になり、他のすべてのデータがその列にグループ化されます。したがって、複数のデータが存在する可能性がありtaskますrun。他の列を選択するだけで、ランダムな結果が選択されます。maxまたはmin、またはsumそれらを連結するなど、そのグループから特定の結果を選択する必要があります。

于 2012-10-28T12:18:58.953 に答える