Поведение MySQL GROUP BY

Если вы просто хотите узнать, сколько времени занимает выполнение команды, вы можете рассмотреть возможность использования команды time . Вы, например, используете time ffmpeg -i myvideoofoneminute.aformat out.anotherformat

15
задан OMG Ponies 29 October 2009 в 20:08
поделиться

6 ответов

MySQL chooses a row arbitrarily. In practice, commonly used MySQL storage engines return the values from the first row in the group, with respect to the physical storage.

create table foo (id serial primary key, category varchar(10));

insert into foo (category) values 
  ('foo'), ('foo'), ('foo'), ('bar'), ('bar'), ('bar');

select * from foo group by category;

+----+----------+
| id | category |
+----+----------+
|  4 | bar      |
|  1 | foo      |
+----+----------+

Other folks are correct that MySQL allows you to run this query even though it has arbitrary and potentially misleading results. The SQL standard, and most other RDBMS vendors, disallow this kind of ambiguous GROUP BY query. This is called the Single-Value Rule: all columns in the select-list must be explicitly part of the GROUP BY criteria, or else inside an aggregate function, e.g. COUNT(), MAX(), etc.

MySQL supports a SQL mode ONLY_FULL_GROUP_BY that makes MySQL return an error if you try to run a query that violates SQL standard semantics.

AFAIK, SQLite is the only other RDBMS that allows ambiguous columns in a grouped query. SQLite returns values from the last row in the group:

select * from foo group by category;

6|bar
3|foo

We can imagine queries that would not be ambiguous, yet still violate the SQL standard semantics.

SELECT foo.*, parent_of_foo.* 
FROM foo JOIN parent_of_foo 
  ON (foo.parent_id = parent_of_foo.parent_id) 
GROUP BY foo_id;

There's no logical way this could produce ambiguous results. Each row in foo gets its own group, if we GROUP BY the primary key of foo. So any column from foo can have only one value in the group. Even joining to another table referenced by a foreign key in foo can have only one value per group, if the groups are defined by the primary key of foo.

MySQL and SQLite trust you to design logically unambiguous queries. Formally, every column in the select-list must be a functional dependency of the columns in the GROUP BY criteria. If you don't adhere to this, it's your fault. :-)

Standard SQL is more strict and disallows some queries that could be unambiguous--probably because it would be too complex for the RDBMS to be sure in general.

27
ответ дан 1 December 2019 в 01:38
поделиться

It is undefined, which result you are going to get.

I was always wondering why this behaviour was even allowed. Really, I wish such code would just generate an error (preferrably, a decipherable one, none of that usual MySQL's "your statement has a problem, but I don't know where" stuff).

3
ответ дан 1 December 2019 в 01:38
поделиться

In standard SQL, This SQL should fail, with a server processor error something like

"firstname, and lastname cannot be included in the select clause unless they are also in the group By, or are part of an aggregate function."

Does MySql actually return data for this ?

0
ответ дан 1 December 2019 в 01:38
поделиться

Весьма вероятно, что будут выбраны имя и фамилия второй (последней) строки.

Вы можете добавить предложение ORDER BY, чтобы дать подсказки о том, как вы хотите сгруппировать строки для сортировки.

0
ответ дан 1 December 2019 в 01:38
поделиться

MySQLs group by не соответствует стандартному поведению SQL, MySQL упрощает получение других столбцов, НО в то же время вы никогда не можете быть уверены, какой из них вы получите.

Обновление : обратитесь к этой странице: http://dev.mysql.com/doc/refman/5.0/en/group-by-handling.html

При использовании этой функции все строки в каждая группа должна иметь одинаковые значения для столбцов, которые исключены из часть GROUP BY. Сервер бесплатный чтобы вернуть любое значение из группы, поэтому результаты неопределенны, если только все значения одинаковы.

4
ответ дан 1 December 2019 в 01:38
поделиться

MySQLs group by is not consistent with the standard SQL behaviour , MySQL makes it easy to get other columns BUT at the same time u Никогда нельзя быть уверенным, что именно вы получите.

Верно. На самом деле это больше соответствует режиму SELECT DISTINCT ON в postgres, например, за исключением того, что он позволяет вам указать порядок строк до выделения (?) И, следовательно, какую строку вы получите (т.е. самую последнюю, самую старую, что угодно).

Примечание. MySQL в режиме "sql-совместимого" отклонит GROUP BY с неуказанными столбцами, как в вашем примере.

0
ответ дан 1 December 2019 в 01:38
поделиться
Другие вопросы по тегам:

Похожие вопросы: