Mysql
 SQL >> Datenbank >  >> RDS >> Mysql

Warum PostgreSQL GROUP BY anders verhält als MySQL

MySQLs nicht standardkonformes GROUP BY lässt sich in PostgreSQL mit DISTINCT ON nachbilden.

MySQL:

SELECT a, b, c, d, e FROM table GROUP BY a

Es wird eine Zeile pro a-Wert zurückgegeben, aber welche Zeile gewählt wird, ist undefiniert.

PostgreSQL:

SELECT DISTINCT ON (a) a, b, c, d, e
FROM table
ORDER BY a, b, c

Auch hier gibt es eine Zeile pro a-Wert, jedoch deterministisch die erste gemäß ORDER BY. Da kein Aggregat berechnet wird, ist DISTINCT ON die passendere Konstruktion.