MySQL创建数据表
概述
创建表是数据库设计的基础。表以行和列的形式存储数据,每列都有特定的数据类型。本章介绍如何创建具有各种选项、约束和设置的表。
表的概念
行:单条记录 列:具有数据类型的属性 主键:唯一标识符 外键:对另一个表的引用 约束:数据的规则 索引:性能结构
CREATE TABLE语法
基本语法
sql
简单示例
sql
完整语法
sql
列定义
数据类型
sql
-- Numeric types
-- String types
-- Date/Time types
-- Other types列选项
sql
自增列
sql
-- Set starting value
-- Change auto_increment value约束
主键约束
sql
-- Single column primary key
-- Composite primary key
-- Add primary key to existing table外键约束
sql
-- Create parent table
-- Create child table with foreign key
-- Foreign key options
-- ON DELETE: RESTRICT, CASCADE, SET NULL, NO ACTION
-- ON UPDATE: RESTRICT, CASCADE, SET NULL, NO ACTION唯一约束
sql
-- Single column unique
-- Multiple columns unique
-- Add unique constraint非空约束
sql
检查约束
sql
-- MySQL 8.0+ CHECK constraint
-- Named constraint
-- Add check constraint默认值
sql
表选项
存储引擎
sql
-- InnoDB (default in MySQL 8.0)
-- MyISAM
-- Memory (for temporary data)字符集和排序规则
sql
自增设置
sql
注释
sql
从另一个表创建表
CREATE TABLE AS / CREATE TABLE AS
sql
-- Create table from SELECT
-- Create with specific columns
-- Create empty table with structure
-- Copy structure and data
-- With WHERE condition临时表
sql
-- Session temporary table
-- Transaction-scoped temporary table示例
用户表
sql
订单表
sql
管理表
显示表
sql
-- List tables
-- List tables with pattern
-- List tables from specific database
-- Describe table structure修改表
sql
-- Add column
-- Add column with position
-- Drop column
-- Modify column
-- Rename column
-- Add constraint
-- Drop constraint
-- Rename table删除表
sql
-- Drop table
-- Drop if exists
-- Drop multiple tables
-- Drop with CASCADE (in some contexts)小结
在MySQL中创建表涉及:
列定义:数据类型和选项 约束:主键、外键、唯一、检查 表选项:引擎、字符集、注释 临时表:会话范围的表 表管理:显示、修改、删除
上一个:选择数据库
下一个:删除表