2015-11-10 2 views
1

Предположим, у меня есть эта таблица: с именем = the_table структура которого:Групповое предложение в mySQL и postgreSQL, почему ошибка в postgreSQL?

PostGreSQL:

create table the_table (col3 SERIAL, col2 varchar, col1 varchar, PRIMARY KEY(col3)); 

MySQL:

create table the_table (col3 INT NOT NULL AUTO_INCREMENT PRIMARY KEY, col2 varchar(20), col1 varchar(20)) 

Затем я вставил таблицу:

INSERT INTO the_table (col2,col1) VALUES 
('x','a'), 
('x','b'), 
('y','c'), 
('y','d'), 
('z','e'), 
('z','f'); 

Теперь таблица выглядит следующим образом:

col3 | col2 | col1 
------+------+------ 
    1 | x | a 
    2 | x | b 
    3 | y | c 
    4 | y | d 
    5 | z | e 
    6 | z | f 

Когда я делаю этот запрос:

select * from the_table group by col2 

затем в MySQL я получаю:

1 x a 
3 y c 
5 z e 

и PostGreSQL, я получаю сообщение об ошибке:

ERROR: column "the_table.col3" must appear in the GROUP BY clause or be used in an aggregate function 
LINE 1: select * from the_table group by col2; 

Мои вопросы:

Что означает эта ошибка? Что такое агрегатная функция?

Когда он работает в MySQL, почему он не может работать в postgreSQL?

+0

Он работает в MySQL, потому что MySQL не работает. , , в том смысле, что MySQL поддерживает расширение, которое запрещено стандартом и не поддерживается в большинстве других баз данных. –

ответ

4

Вы должны использовать AGGREGATE FUNCTION:

Aggregate functions compute a single result from a set of input values.

SELECT col2, MIN(col3) AS col3, MIN(col1) AS col1 
FROM the_table 
GROUP BY col2; 

SqlFiddleDemo

MySQL Handling of GROUP BY:

In standard SQL, a query that includes a GROUP BY clause cannot refer to nonaggregated columns in the select list that are not named in the GROUP BY clause

и:

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

Так с версии MySQL без явного агрегатной функции вы можете в конечном итоге с undetermininistic значениями. Я настоятельно рекомендую использовать определенную совокупную функцию.

0

Пожалуйста, используйте его:

select DISTINCT ON (col2) col2, col1, col3 from the_table 

Мой результат:

"x";"a";1 
"y";"c";3 
"z";"e";5 
Смежные вопросы