插入一条记录
insert into customers(
customer_id,
first_name,
last_name,
birth_date,
phone,
address,
city,
state,
points)
values (
default, -- 按顺序
'cfd',
'best',
'2023-10-7',
NULL,
'1716',
'university',
'ok',
default
)
- 每一列和
values里面的内容按顺序一一对应 - 默认或者是NULL的就可以不写,和列名一起删除,不写的就是默认
插入多条记录
VALUES …… 里一行内数据用括号内逗号隔开,而多行数据用括号间逗号隔开
USE sql_store;
INSERT INTO products
VALUES (DEFAULT, 'product1', 1, 10),
(DEFAULT, 'product2', 2, 20),
(DEFAULT, 'product3', 3, 30)
或
INSERT INTO products (name, quantity_in_stock, unit_price)
VALUES ('product1', 1, 10),
('product2', 2, 20),
('product3', 3, 30)
还是感觉后面这种指明列名的要清晰一点
注意
对于AI (Auto Incremental 自动递增) 的id字段,MySQL会记住删除的/用过的id,并在此基础上递增
插入分级行
订单表(orders表)里的一条记录对应订单项目表(order_items表)里的多条记录,一对多,是相互关联的父子表。
- 关键:在插入子表记录时,需要用内建函数
LAST_INSERT_ID()获取相关父表记录的自增ID(这个例子中就是 order_id) - 内建函数:MySQL里有很多可用的内置函数,也就是可复用的代码块,各有不同的功能,注意函数名的单词之间用下划线连接
LAST_INSERT_ID():获取最新的成功的INSERT 语句中的自增id,在这个例子中就是父表里新增的 order_id。
insert into orders (customer_id,order_date, status)
values (1,'2020-10-7',1);
select last_insert_id();
insert into order_items
values (last_insert_id(),1,1,2.95) , -- 获取插入记录的id
(last_insert_id(),2,1,3.95)
复制表
-
DROP TABLE 要删的表名 -
CREATE TABLE 新表名 AS 子查询 -
TRUCATE '要清空的表名' -
INSERT INTO 表名 子查询
create table orders_archived as
select * from orders;
-- 复制另一张表中的一部分数据
insert into orders_archived
select *
from orders
where order_date < '2019-01-01'
use sql_invoicing;
create table invoices_archived as
SELECT i.invoice_id, c.name AS client, i.payment_date
from invoices i
join clients c
using (client_id)
where payment_date is not null
更新
更新单行
UPDATE 表
SET 要修改的字段 = 具体值/NULL/DEFAULT/列间数学表达式 (修改多个字段用逗号分隔)
WHERE 行筛选
use sql_invoicing;
update invoices
set payment_total = 10,
payment_date = '2019-03-01'
where invoice_id = 1;
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 = 1
更新多行
和上面用法一样,只需要修改 where 中条件就可以。 去掉where条件,就是默认对所有的记录操作
update invoices
set payment_total = invoice_total * 0.5,
payment_date = due_date
where invoice_id in (3,4);
在update中使用子查询
在更新的 where 后面加上一个 查询即可 可以是
- in (多个返回修改)
- is not / is
- = (单个返回修改)
update invoices
set payment_total = invoice_total * 0.5,
payment_date = due_date
where client_id in
(select client_id
from clients
where name in ('CA','NY'))
UPDATE orders
SET comments = 'gold customer'
WHERE customer_id IN
(SELECT customer_id
FROM customers
WHERE points > 3000)
删除行
和更新非常相似
delete from invoices
where invoice_id = 1;
delete from invoices
where invoice_id = (
select *
from clients
where name = 'Myworks')