04 MySQL插入

单行插入

insert into

insert intovalues ()

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

updateset 列名 = , .... ,  .
where id = 

set指定一列或者多列的新值

更新多行

在上一个语句中的条件中改为针对多行的就可以了

updateset 列名 = , .... ,  .
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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值