Home > Database > Mysql Tutorial > PostgreSQL vs. MySQL GROUP BY: How to Achieve MySQL's Grouping Behavior in PostgreSQL?

PostgreSQL vs. MySQL GROUP BY: How to Achieve MySQL's Grouping Behavior in PostgreSQL?

Patricia Arquette
Release: 2025-01-11 08:24:42
Original
812 people have browsed it

PostgreSQL vs. MySQL GROUP BY: How to Achieve MySQL's Grouping Behavior in PostgreSQL?

Differences in GROUP BY between PostgreSQL and MySQL

There are differences in the GROUP BY syntax of MySQL and PostgreSQL, which often leads to errors such as "Column X must appear in the GROUP BY clause".

MySQL’s GROUP BY behavior

In MySQL, the following query will return a row for each unique value in the bookdate column:

<code class="language-sql">SELECT `availables`.*
FROM `availables`
INNER JOIN `rooms` ON `rooms`.id = `availables`.room_id
WHERE (rooms.hotel_id = 5056 AND availables.bookdate BETWEEN '2009-11-22' AND '2009-11-24')
GROUP BY availables.bookdate
ORDER BY availables.updated_at</code>
Copy after login

GROUP BY requirements for PostgreSQL

However, in PostgreSQL, columns that are not explicitly included in the GROUP BY clause or used in aggregate functions must be part of the primary key. In the above query, availables.id is neither included in the GROUP BY nor used in the aggregation, thus causing the error.

Simulate MySQL behavior

In order to simulate MySQL's GROUP BY behavior in PostgreSQL, you can use DISTINCT ON instead of GROUP BY:

<code class="language-sql">SELECT DISTINCT ON (availables.bookdate) availables.*
FROM availables
INNER JOIN rooms ON rooms.id = availables.room_id
WHERE (rooms.hotel_id = 5056 AND availables.bookdate BETWEEN '2009-11-22' AND '2009-11-24')
ORDER BY availables.bookdate, availables.updated_at</code>
Copy after login

DISTINCT ON ensures the uniqueness of the specified columns while preserving the order specified in the ORDER BY clause. This syntax simulates MySQL's ability to return a single row of records by a unique value in the bookdate column.

The above is the detailed content of PostgreSQL vs. MySQL GROUP BY: How to Achieve MySQL's Grouping Behavior in PostgreSQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template