JSON Column - Khi NoSQL gặp SQL

Dùng JSON column khi nào - góc nhìn thiết kế schema.

Dùng khi

  • Dữ liệu ít khi query trực tiếp (metadata, settings)
  • Thay thế bảng EAV (Entity-Attribute-Value) phức tạp
  • Giảm số lượng JOIN cho data seldom-used

Quy tắc

  • Vẫn dùng relational cho data chính (foreign key, constraints)
  • Tránh deeply nested JSON: query/update sẽ rất phức tạp
  • Cân nhắc kỹ khi lưu references đến bảng khác trong JSON (mất FK constraint)

JSON Schema Validation (MySQL)

Ràng buộc cấu trúc JSON ngay ở tầng database:

ALTER TABLE products ADD CONSTRAINT CHECK(
    JSON_SCHEMA_VALID('{
        "type": "object",
        "properties": {
            "tags": {"type": "array", "items": {"type": "string"}}
        },
        "additionalProperties": false
    }', attributes)
);

Liên quan