DevToolBox免费
博客

PostgreSQL vs MySQL 2026: 应该选择哪个数据库?

11分钟作者 DevToolBox

在后端开发中,选择 PostgreSQL 还是 MySQL 是最重要的决策之一。两者都是开源、成熟、经过生产验证的关系型数据库。

快速概览

PostgreSQL 优先考虑标准合规性、数据完整性和可扩展性。MySQL 优先考虑简洁性和读密集型工作负载的速度。

Feature              PostgreSQL          MySQL 8.x
------------------------------------------------------------
License              PostgreSQL (free)   GPL / Commercial
ACID Compliance      Full                Full (InnoDB)
JSON Support         JSONB (excellent)   JSON (good)
Full-Text Search     Built-in tsvector   FULLTEXT index
Replication          Streaming + Logical Binary log + GTID
Max DB Size          Unlimited           256TB
Partitioning         Declarative         RANGE/LIST/HASH
Window Functions     Full support        Partial (8.x+)
Extensions           Rich ecosystem      Plugins (fewer)
Default in Cloud     Supabase, RDS       PlanetScale, RDS

功能对比

PostgreSQL 历来拥有更丰富的功能集。MySQL 在 8.x 版本中大幅缩小了差距。

-- Feature Comparison: PostgreSQL vs MySQL

-- 1. JSON Support
-- PostgreSQL JSONB (binary, indexed)
SELECT data->>'name' FROM users WHERE data @> '{"active": true}';
CREATE INDEX idx_users_data ON users USING GIN (data);

-- MySQL JSON
SELECT JSON_EXTRACT(data, '$.name') FROM users
WHERE JSON_EXTRACT(data, '$.active') = true;

-- 2. Full-Text Search
-- PostgreSQL (built-in tsvector)
SELECT * FROM articles
WHERE to_tsvector('english', content) @@ to_tsquery('postgresql & performance');

-- MySQL FULLTEXT
SELECT * FROM articles
WHERE MATCH(content) AGAINST ('postgresql performance' IN NATURAL LANGUAGE MODE);

-- 3. CTEs (Common Table Expressions)
-- PostgreSQL supports recursive CTEs natively (since 8.4)
WITH RECURSIVE category_tree AS (
  SELECT id, name, parent_id, 0 AS level
  FROM categories WHERE parent_id IS NULL
  UNION ALL
  SELECT c.id, c.name, c.parent_id, ct.level + 1
  FROM categories c JOIN category_tree ct ON c.parent_id = ct.id
)
SELECT * FROM category_tree ORDER BY level, name;

-- 4. Window Functions (both support, PostgreSQL more complete)
SELECT
  employee_id,
  salary,
  AVG(salary) OVER (PARTITION BY department_id) as dept_avg,
  RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) as rank
FROM employees;

性能对比

原始性能在很大程度上取决于工作负载类型。

-- Performance Tuning Examples

-- PostgreSQL: EXPLAIN ANALYZE
EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)
SELECT u.id, u.name, COUNT(o.id) as order_count
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
WHERE u.created_at > '2025-01-01'
GROUP BY u.id, u.name
ORDER BY order_count DESC
LIMIT 100;

-- PostgreSQL-specific indexes
CREATE INDEX CONCURRENTLY idx_orders_user_status
ON orders (user_id, status)
WHERE status != 'cancelled';  -- Partial index

CREATE INDEX idx_products_attrs ON products USING GIN (attributes); -- JSONB index

-- MySQL: EXPLAIN FORMAT=JSON
EXPLAIN FORMAT=JSON
SELECT u.id, u.name, COUNT(o.id) as order_count
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
WHERE u.created_at > '2025-01-01'
GROUP BY u.id, u.name
ORDER BY order_count DESC
LIMIT 100;

-- Connection pooling configuration
-- PostgreSQL (PgBouncer or pg pool settings)
max_connections = 100           -- in postgresql.conf
-- Use connection pooler for high concurrency
-- PgBouncer pool_mode = transaction  (recommended for web apps)

-- MySQL
max_connections = 200           -- in my.cnf
innodb_buffer_pool_size = 4G    -- 70-80% of RAM for dedicated MySQL server

何时选择 PostgreSQL

当需要高级 SQL 功能、数据完整性保证或复杂查询能力时,PostgreSQL 是正确的选择。

  • Complex queries — Advanced window functions, CTEs, lateral joins
  • JSON/document storage — JSONB with GIN indexes rivals MongoDB
  • Geospatial data — PostGIS extension is the gold standard
  • Strict data integrity — CHECK constraints, exclusion constraints, custom domains
  • High-concurrency writes — MVCC handles concurrent writes better than MySQL
  • Full-text search — Built-in, no external service needed
  • Analytics/reporting — Better at complex aggregations and window functions

何时选择 MySQL

MySQL 对于许多用例仍然是极好的选择,特别是读密集型 Web 应用。

  • Simple CRUD applications — WordPress, Drupal, and many CMSes default to MySQL
  • Read-heavy workloads — InnoDB is highly optimized for read-heavy patterns
  • Existing MySQL ecosystem — If your team has deep MySQL expertise
  • PlanetScale — MySQL-compatible serverless database with excellent DX
  • Replication simplicity — MySQL replication is well-understood and widely deployed

数据库迁移

从 MySQL 迁移到 PostgreSQL(或反向)需要仔细规划 SQL 方言差异和数据类型映射。

-- MySQL to PostgreSQL Migration: Common Differences

-- 1. AUTO_INCREMENT -> SERIAL/IDENTITY
-- MySQL
CREATE TABLE users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100)
);

-- PostgreSQL
CREATE TABLE users (
  id SERIAL PRIMARY KEY,  -- or BIGSERIAL for large tables
  name VARCHAR(100)
);
-- Modern PostgreSQL (v10+):
-- id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY

-- 2. String functions differ
-- MySQL: IFNULL
SELECT IFNULL(phone, 'N/A') FROM users;
-- PostgreSQL: COALESCE (also works in MySQL)
SELECT COALESCE(phone, 'N/A') FROM users;

-- 3. String concatenation
-- MySQL
SELECT CONCAT(first_name, ' ', last_name) FROM users;
-- PostgreSQL
SELECT first_name || ' ' || last_name FROM users;
-- Or use CONCAT (PostgreSQL also supports it)

-- 4. LIMIT/OFFSET syntax (both support the same)
SELECT * FROM users ORDER BY id LIMIT 10 OFFSET 20;

-- 5. Boolean values
-- MySQL: TRUE/FALSE or 1/0
-- PostgreSQL: TRUE/FALSE or 't'/'f' or 'true'/'false'

-- 6. Timestamp with timezone
-- MySQL: DATETIME or TIMESTAMP (local time only)
-- PostgreSQL: TIMESTAMPTZ (timezone-aware, recommended)
ALTER TABLE events
  ALTER COLUMN created_at TYPE TIMESTAMPTZ
  USING created_at AT TIME ZONE 'UTC';

常见问题

PostgreSQL 比 MySQL 快吗?

取决于工作负载。MySQL 对简单读查询通常更快。PostgreSQL 在复杂分析查询、高并发写入方面表现更好。

主要云提供商推荐哪个数据库?

所有主要云提供商都提供两者。Supabase 基于 PostgreSQL,PlanetScale 基于 MySQL。

PostgreSQL 支持 JSON 吗?

是的,PostgreSQL 通过 JSONB 类型提供出色的 JSON 支持,以二进制格式存储并支持索引。

2026 年新项目应该选哪个?

对于 2026 年大多数新项目,推荐 PostgreSQL 作为默认选择。

相关工具

𝕏 Twitterin LinkedIn
这篇文章有帮助吗?

保持更新

获取每周开发技巧和新工具通知。

无垃圾邮件,随时退订。

试试这些相关工具

{ }JSON FormatterSQLSQL Formatter

相关文章

MongoDB vs PostgreSQL:2026 年该选哪个数据库?

MongoDB 和 PostgreSQL 详细对比。数据建模、性能、扩展、CRUD 操作、ORM 支持和决策矩阵,帮助你选择正确的数据库。

SQL vs NoSQL:选择正确数据库的完整指南

理解 SQL 与 NoSQL 数据库的区别,比较 PostgreSQL、MongoDB、Redis 的使用场景。

PostgreSQL 性能调优:索引策略、查询优化与配置

PostgreSQL 性能调优完全指南 — 索引策略、EXPLAIN ANALYZE、连接池和服务器配置。