- 如果在插入记录前,删除了原有最后记录行,如最后一行的id为12,新插入的数据id会从13开始。
1. 插入单行 INSERT INTO
- customers表结构
INSERT INTO customers (
first_name,
last_name,
birth_date,
address,
city,
state)
VALUES (
'John',
'Smith',
'1990-01-01',
'address',
'city',
'VA')
- 结果显示:插入了一条customer_id为11的记录,customer_id自增。
2. 插入多行
- shippers表结构
INSERT INTO shippers (name)
VALUES ('shipper1'),
('shipper2'),
('shipper3')
- 结果显示:插入了shipper_id为6、7、8的三条记录,shipper_id自增
3. 插入分层行
- 往多张表中插入数据,或者是往两个互为亲子关系的表中插入数据,使用到数据库引擎自带的内容功能 LAST_INSERT_ID() 最近插入的id
INSERT INTO orders (customer_id,order_date,status)
VALUES (1,'2021-11-26',1);
INSERT INTO order_items
VALUES (LAST_INSERT_ID(),1,1,2.95),
(LAST_INSERT_ID(),2,1,3.95)
4. 创建表复制 快速将数据从一张表复制到另一张新表
- 创建表复制的缺点,MySQL会忽略id的主键和自增属性,手动到设计模式中勾上。
- 创建表复制的书写步骤,先写子查询确认查询的内容正确,再写CREATE TABLE
CREATE TABLE orders_archived AS
SELECT * FROM orders;
INSERT INTO orders_archived
SELECT *
FROM orders
WHERE order_date > '2019-01-01';
5. 更新单行 UPDATE
UPDATE invoices
SET payment_total = DEFAULT,
payment_date = NULL
WHERE invoice_id = 1;
UPDATE invoices
SET payment_total = invoice_total * 0.5,
payment_date = due_date
WHERE invoice_id = 3;
6. 更新多行
- MySQL Workbentch软件执行更新多行记录会报错,其他的应用程序不会;可以通过以下方式解决,记得保存后重新连接MySQL instance才奏效。这原本是防止意外更新或删除了一些记录。
UPDATE invoices
SET payment_total = invoice_total * 0.5,
payment_date = due_date
WHERE client_id = 3;
7. 在UPDATE语句中使用子查询
使用子查询或者更新的条件不是确切值时,一定要先执行选择语句,检查是否是要更新的记录,只有确定是要更新的记录,再执行更新语句!!!
UPDATE invoices
SET
payment_total = invoice_total * 0.5,
payment_date = due_date
WHERE client_id =
(SELECT client_id
FROM clients
WHERE name = 'Myworks');
UPDATE invoices
SET
payment_total = invoice_total * 0.5,
payment_date = due_date
WHERE client_id IN
(SELECT client_id
FROM clients
WHERE state IN ('NY','CA'));
UPDATE invoices
SET
payment_total = invoice_total * 0.5,
payment_date = due_date
WHERE payment_date IS NULL;
8. 删除行 DELETE
DELETE FROM invoices;
DELETE FROM invoices
WHERE invoice_id = 1;
DELETE FROM invoices
WHERE client_id =
(SELECT client_id
FROM clients
WHERE name = 'Myworks');
9. 恢复数据库
File----->Open SQL Script----->在存储SQL脚本的目录位置选择要恢复的数据库----->执行脚本
|