关系型数据库 vs 非关系型数据库
Relational database vs Non-relational database
一句话:关系型先定好表结构、用 JOIN 关联、 强调一致性; 非关系型结构灵活、 按查询模式组织数据、 强调扩展性。
| 关系型(MySQL、PostgreSQL) | 非关系型(MongoDB、Redis) | |
|---|---|---|
| 结构 | 表 + 行 + 列,schema 固定 | 文档 / 键值 / 图,schema 灵活 |
| 关联 | JOIN | 嵌套文档,或应用层自己拼 |
| 事务 | ACID 是强项 | 有但较弱(MongoDB 4.0+ 支持多文档事务) |
| 扩展 | 纵向为主(加配置),分库分表麻烦 | 横向为主(加机器) |
| 适合 | 数据关系复杂、要强一致—— 订单、账务、库存 | 结构多变、读多写多、 单次查询取一整块—— 日志、内容、会话、缓存 |
选型的正确说法:「看数据形状和访问模式」——
- 一次查询要取的东西总是在一起(一篇文章连着它的所有段落)→ 文档型合适。
- 同一份数据要从很多角度关联查(用户 × 订单 × 商品 × 优惠券)→ 关系型合适,因为文档型要么冗余存多份、要么在应用层做 JOIN。
- 需要转账那样的强一致 → 关系型。
会追问:「MongoDB 没有 schema 是优点吗?」——是双刃剑。 前期迭代快,但约束跑到了应用层, 时间长了同一个集合里会存在好几代不同形状的文档。 所以实践中一般还是用 Mongoose 这类工具在应用层加回 schema。
「现在还有清楚的界限吗?」—— 在模糊:PostgreSQL 的jsonb 让它能存文档并建索引, 所以「先上 Postgres, 需要文档就用 jsonb」是很常见的现实选择。
In one line: relational means you define the schema up front, relate rows with JOINs, and lean on consistency; non-relational means a flexible shape, data laid out for the queries you actually run, and easier scale-out.
| Relational (MySQL, PostgreSQL) | Non-relational (MongoDB, Redis) | |
|---|---|---|
| Shape | Tables, rows, columns — fixed schema | Documents / key-value / graph — flexible schema |
| Relating data | JOIN | Nested documents, or you stitch it in the app |
| Transactions | ACID is the whole point | Present but weaker (MongoDB 4.0+ has multi-document) |
| Scaling | Mostly vertical; sharding is painful | Mostly horizontal — add machines |
| Good for | Complex relationships and strong consistency — orders, ledgers, inventory | Shifting shapes, heavy read and write, one query pulling a whole blob — logs, content, sessions, caches |
The right way to talk about choosing: “Look at the shape of the data and the access pattern.”
- Everything one query needs always travels together (an article and all its paragraphs) → document store fits.
- The same data gets related from many angles (users × orders × products × coupons) → relational fits, because a document store either duplicates it or makes you JOIN in application code.
- You need transfer-money-level consistency → relational.
Follow-up: “Is MongoDB being schema-less an advantage?” — it cuts both ways. You move faster early on, but the constraints move into your application code, and given enough time one collection holds three generations of document shapes. Which is why teams reach for something like Mongoose to put a schema back on top.
“Is the line still clear today?” — it is blurring. PostgreSQL’s jsonb stores documents and indexes them, so “start on Postgres, use jsonb where you need a document” is a very common real-world answer.