MySQL插入数据
概述
INSERT语句用于向表中添加新行。本章介绍插入数据的各种方式,包括单行、多行以及从其他表插入。
INSERT语法选项
sql
基本插入
插入单行
sql
-- Specify columns
-- Omit optional columns (they use DEFAULT or NULL)
-- Insert all columns
-- Insert with DEFAULT for optional columns插入多行
sql
-- Multiple values in single statement
-- Can insert hundreds of rows efficiently使用SET插入
sql
-- Using SET clause
-- Useful for inserting from application variables使用SELECT插入
从另一个表复制
sql
-- Insert all columns
-- Insert specific columns
-- Insert with transformations
-- Insert distinct values从查询批量插入
sql
-- Insert aggregated data
-- Insert from multiple sources冲突时更新
基本语法
sql
示例
sql
-- Insert or update if email already exists
-- Increment counter
-- Multiple columns使用VALUES()函数
sql
-- Reference values being inserted
-- Use VALUES() to reference original value忽略错误
基本用法
sql
-- Skip rows that cause duplicate key or constraint errors
-- Handle duplicates gracefully用例
sql
-- Import from external source
-- Sync data from another system替换
基本用法
sql
-- REPLACE works like INSERT but deletes existing row first
-- If id=1 exists, it's deleted and new row inserted
-- If id=1 doesn't exist, new row is inserted
-- REPLACE with SELECT比较
| 方面 | REPLACE | ON DUPLICATE KEY UPDATE |
|---|---|---|
| 行为 | Deletes old row | Updates old row |
| 自增 | New value generated | Preserved |
| 触发器 | DELETE then INSERT | Only UPDATE |
| 性能 | Faster | Slower |
| 外键 | More complex | Simpler |
批量插入优化
批量插入
sql
-- Insert thousands of rows efficiently
-- ... up to millions of rows编程示例
Python / Python
python
# Batch insert with executemany
# ... more rows
# Efficient batch insertPHP / PHP
php
插入特定值
自增列
sql
-- Insert with explicit auto-increment value
-- Insert without specifying auto-increment
-- Get last insert ID
-- In application
-- Python: cursor.lastrowid
-- PHP: $conn->insert_id时间戳
sql
-- Insert with current timestamp
-- Insert with specific timestamp
-- Insert with NULL for timestamp空值
sql
-- Insert NULL explicitly
-- Insert with DEFAULT for nullable columns
-- Check NULL after insertRETURNING子句
MySQL 8.0+ / MySQL 8.0+
sql
-- Get inserted/updated values
-- With ON DUPLICATE KEY故障排除
常见错误
sql
-- Duplicate entry
-- Error: Duplicate entry 'value' for key 'unique_key'
-- Solution: Use INSERT IGNORE or ON DUPLICATE KEY
-- Data too long
-- Error: Data too long for column 'name'
-- Solution: Check column size or truncate data
-- Incorrect integer value
-- Error: Incorrect integer value
-- Solution: Check data types match
-- Cannot add or update child row
-- Error: Foreign key constraint fails
-- Solution: Insert parent record first
-- Table doesn't exist
-- Error: Table 'table_name' doesn't exist
-- Solution: Create table first or check name调试插入
sql
-- Check table structure
-- Check data types
-- Test with simple values
-- Check auto-increment小结
MySQL中插入数据包括:
基本插入:单行和多行 SELECT插入:从其他表复制 冲突时更新:插入或更新 忽略插入:跳过重复 替换:替换现有行 批量操作:高效的批量插入 返回:获取插入的值
上一个:删除表
下一个:查询数据