前言
前面我們學(xué)習(xí)了MySQL——DDL操作,對(duì)數(shù)據(jù)庫(kù)和表的結(jié)構(gòu)的操作,那么今天我將為大家分享MySQL——DML操作,對(duì)表數(shù)據(jù)的操作。
MySQL DML操作有以下幾種:
-
插入操作(INSERT):用于向數(shù)據(jù)庫(kù)中插入新的數(shù)據(jù)行??梢砸淮尾迦雴涡袛?shù)據(jù),也可以使用一條SQL語(yǔ)句一次性插入多行數(shù)據(jù)。
-
更新操作(UPDATE):用于修改數(shù)據(jù)庫(kù)中已有的數(shù)據(jù)行??梢愿鶕?jù)指定的條件更新滿(mǎn)足條件的數(shù)據(jù)行。
-
刪除操作(DELETE):用于從數(shù)據(jù)庫(kù)中刪除數(shù)據(jù)行??梢愿鶕?jù)指定的條件刪除滿(mǎn)足條件的數(shù)據(jù)行。
插入數(shù)據(jù)
MySQL中,向1表中插入數(shù)據(jù)的方式有兩種:insert into 表名 values (值1,值2,值3);
和 insert into 表名 (列名1,列名2) values (值1,值2);
全列插入
第一種插入方式是插入所有列的數(shù)據(jù) insert into 表名 values (值1,值2,值3);
,并且列的數(shù)據(jù)需要跟列的位置相對(duì)應(yīng)。
create table student(
id int,
name varchar(20),
chinese decimal(3,1),
math decimal(3,1),
english decimal(3,1));
insert into student values(01,'張三',85,95.5,90);
如果需要添加的數(shù)據(jù)很多,我們是不是也只能一個(gè)一個(gè)的添加呢?當(dāng)然不是,我們可以一次添加多個(gè)數(shù)據(jù)。每一組數(shù)據(jù)之間使用逗號(hào) , 分隔。
insert into student values(02,'李四',87,97.5,87.5),
(03,'王五',88,90,96);
指定列插入
有些時(shí)候,插入數(shù)據(jù)的時(shí)候,不需要插入所有列的數(shù)據(jù),而是可以指定列來(lái)插入 insert into 表名 (列名1,列名2) values (值1,值2);
insert into student(name,math) values('李華',98);
沒(méi)有被插入數(shù)據(jù)的列會(huì)是默認(rèn)值。
指定列插入同樣可以一次插入多組數(shù)據(jù)。
insert into student(name,chinese) values('小美',96),
('小帥',92);
修改數(shù)據(jù)
當(dāng)我們添加完數(shù)據(jù)之后,我們可以對(duì)已添加的數(shù)據(jù)進(jìn)行修改。修改全部列的數(shù)據(jù): update 表名 set 列名 值;
,修改指定行的數(shù)據(jù):update 表名 set 列名 值 where 條件;
將所有人的語(yǔ)文成績(jī)加上3分。
update student set chinese = chinese + 3;
將張三的語(yǔ)文成績(jī)減去2分。
update student set english = english - 2 where name = '張三';
刪除數(shù)據(jù)
MySQL 刪除數(shù)據(jù)刪除的是一行的數(shù)據(jù)。在MySQL中刪除數(shù)據(jù)主要有兩種方式:delete from 表名 [where 條件];
和 truncate table 表名 / truncate 表名;
delete from 表名 [where 條件];
刪除數(shù)據(jù)通常搭配著后面的 where
條件語(yǔ)句,如果沒(méi)有后面的 where
條件語(yǔ)句,將會(huì)刪除整個(gè)表。
delete from student;
delete from 表名 where 條件;
刪除符合條件的行數(shù)據(jù)。
delete from student where name = '小美';
truncate table 表名
; / truncate 表名;
刪除表中的所有數(shù)據(jù),它跟 delete 刪除數(shù)據(jù)是有點(diǎn)區(qū)別的,當(dāng) delete 刪除表中的所有數(shù)據(jù)時(shí),只是刪除了表中的所有數(shù)據(jù),而 truncate 刪除數(shù)據(jù)類(lèi)似于 drop table 表名
,它會(huì)先將表給刪除,然后再創(chuàng)建一個(gè)沒(méi)有數(shù)據(jù)的空表。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-614213.html
truncate table student;
truncate student;
文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-614213.html
到了這里,關(guān)于MySQL數(shù)據(jù)庫(kù)——DML基本操作的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!