Mysql8.0学习笔记(3)——insert into,update...set,delete

简介

在本章前先了解下table的属性,还是以customers为例,点击表旁边的扳手获得如下图
在这里插入图片描述
对于Datatype :

  • INT :只支持数字形式,例如“1234”
  • VARCHAR(50):该类型为字符串格式,空间为变长,最长为50
  • CHAR(2):字符串格式,空间固定为2,不足补空格
  • DATE:日期格式 例如"2020-04-16"

PK:表示为主键
NN:表示不为空,即在这张表里勾选中的不能为空,其他可选
AI:自动增量属性,一般以主键为准,根据插入数据使主键递增
Default/Expression:没输入值的默认值

insert into

  • 插入一行数据
use sql_store;
insert into customers
//因为主键设置AI,默认加1,其他没填写的使用默认值
value(default,"lj",'jiawei','1993-09-22',null,	
	'adress','city','ca',default)
//也可以指定插入哪些值,顺序只要保证对应一致就行
insert into customers(first_name, last_name, birth_date,
	address,city,state)
value("lj",'jiawei','1993-09-22',	
	'adress','city','ca')
  • 插入多行数据
    使用’,'隔开就行
insert into customers(first_name, last_name, birth_date,
	address,city,state)
value("lj",'jiawei','1993-09-22',	
	'adress','city','ca'),
	("lj2",'jiawei2','1993-09-22',	
	'adress','city','ca'),
  • 将数据插入分层表中
    对于一个table,可能有子表来表示其其余的信息,例如订单orders,有子表order_items
    其中order中的customer_id,order——date,status为NN;order_items中的product_id,quantity,unit_price也为NN;order_id都为两个表的主键
    在这里插入图片描述
    在这里插入图片描述
    在插入orders的时候同时也要插入order_items
insert into orders(customer_id,order_date,status)
values(1,'2019-01-02',1);
insert into order_items
//LAST_INSERT_ID()为内置的函数,可以获取上一次插入的主键的值
values(LAST_INSERT_ID(),1,1,2.25),
	(LAST_INSERT_ID(),2,1,2.25)

此时orders与order_items的插入如下

在这里插入图片描述
在这里插入图片描述

  • 复制整张表
//将orders表中的数据全部复制到orders_archived
create table orders_archived as
select * from orders

这里select作为子句完成及其强大的功能
注意:这种方式复制出来的表没有主键,且不支持AI

  • 复制部分表
insert into orders_archived
select * from orders
where order_date < '2019-01-01'
  • 利用联合以及create table构建自己想要的新表,用invoices与clients表显示已经下过订单且显示客户信息
use sql_invoicing;
create table invoices_archived as
select i.invoice_id,i.number,c.name as client,
    i.invoice_total,i.payment_total,i.invoice_date,
    i.payment_date,i.due_date
from invoices i
right join clients c
	on i.client_id = c.client_id
where  i.payment_date is not null

invoices 表
在这里插入图片描述
clients 表
在这里插入图片描述
创建出来的新表invoices_archived
在这里插入图片描述

update

  • 以之前invoice表为例,更新第一行数据
update invoices
set payment_total = 10, payment_date = '2019-03-01'
//set payment_total = default, payment_date = NULL	恢复默认值
where invoice_id  = 1
  • 更新多行数据
  • 只需要更改where的条件就行,不加where表示全表
use sql_invoicing;
update invoices
set 
	payment_total = invoice_total * 0.5,
    payment_date = due_date
where client_id = 3
  • 利用select挑选更新条件
use sql_invoicing;
update invoices
set 
	payment_total = invoice_total * 0.5,
    payment_date = due_date
where client_id in
	(select client_id from where state in ('CA','NY'))

delete

与update类似

delete from invoices
where client_id in
	(select client_id from clients where name = 'Myworks') 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值