单行插入
insert into
insert into 表
values ()
insert into customers
values (
default,
'John',
'Smith',
'1990-01-01',
null,
'address',
'city',
'CA',
default
)
insert into 表 (想要插入的列)
values ()
insert into customers (
first_name,
last_name,
birth_date,
address,
city,
state
)
values (
-- default,
'John',
'Smith',
'1990-01-01',
-- null,
'address',
'city',
'CA',
-- default
)
注意:无论使用第一种方法还是第二种方法,都要与给定的顺序匹配好,如果不指定列,需要与表中的每一列匹配好,指定列就要与指定列匹配好,避免插入错误的列中
多行插入
insert into shippers (name)
values
('1'),
('2'),
('3')
插入分层行
在需要插入相同id的不同表中,我们有的时候需要把某个唯一的主键一齐进行操作(个人理解
例如,订单表中存了关于这个订单的信息,而订单项目保存了这个订单中订购了哪些货物,多少个等等
insert into orders (customer_id, order_date, status)
values (1, '2021-01-01', 1);
insert into order_items (order_id, product_id, quantity, unit_price)
values
(LAST_INSERT_ID(), 1, 1, 3),
(LAST_INSERT_ID(), 2, 1, 5),
LAST_INSERT_ID()
:简单说来,就是这个函数将返回插入的那条记录在表中自增的那个字段的值,一般我们都给那个自增字段命名为ID。这样就可以返回刚插入的记录的ID值了。
复制表
本质是再创建一个新表
create table order_ajlf as
select * from orders
注意,这样复制后,列相关的属性并不会与原表相同
也可以对子查询进行建表
use sql_invoicing;
create table invoices_achieve as
select
DISTINCT clients.name
from invoices inner join clients
on invoices.client_id = clients.client_id
where invoices.payment_date is not null
更新单行
update
update 表 set 列名 = , .... , .
where id =
set
指定一列或者多列的新值
更新多行
在上一个语句中的条件中改为针对多行的就可以了
update 表 set 列名 = , .... , .
where id in () (或一列id有多个那种
update customers
set
points = points + 50
where
birth_date < '1990-01-01'
子查询完成更新
-- 在where后面进行查询操作
update invoices
set
操作
where id = (select from where)
-- 如果查询的值包含多个返回值,应当用in包含起来进行查询
update orders
set
comments = 'golen customers'
where
customer_id in (select customer_id from customers where points > 3000)
删除行
delete from 表名
where