Skip to content

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

比较

方面REPLACEON DUPLICATE KEY UPDATE
行为Deletes old rowUpdates old row
自增New value generatedPreserved
触发器DELETE then INSERTOnly UPDATE
性能FasterSlower
外键More complexSimpler

批量插入优化

批量插入

sql
-- Insert thousands of rows efficiently
    -- ... up to millions of rows

编程示例

Python / Python

python

# Batch insert with executemany
    # ... more rows

# Efficient batch insert

PHP / 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 insert

RETURNING子句

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插入:从其他表复制 冲突时更新:插入或更新 忽略插入:跳过重复 替换:替换现有行 批量操作:高效的批量插入 返回:获取插入的值


上一个:删除表

下一个:查询数据