SQL插入數(shù)據(jù)
查詢表中所有數(shù)據(jù):
select * from 表名;
查詢指定的列:
select 列名1,列名2 from 表名;
例:select name,age from students
插入操作:
insert into 表名(列名1蝙寨,列名2述寡,.....)values (列值1告丢,列值2,.....);
例:insert into students (id,name,age,email,score) values (2,'lisi',18,'zs@aliyun.com',null);
插入多條數(shù)據(jù):
insert into students (id,name,age,email,score) values (2,'zhao',18,'zs@aliyun.com',null),(3,'qian',20,'zs@aliyun',null);
更新數(shù)據(jù):
update 表名 set 列名1=列值1,列名2=列值2,.......where 列名=值;
例:update students set score=60;(把所有的學(xué)生成績(jī)改為60分)
把姓名為zs的學(xué)生分?jǐn)?shù)該為60:
update students set score=60 where name='zs';
把姓名為lisi的年齡修改為20和分?jǐn)?shù)修改為70:
update students set age=20,score=70 where name='lisi';
把wangwu的年齡在原來(lái)的基礎(chǔ)上加一歲:
update student set age=age+1 where name='wangwu';
修改數(shù)據(jù)庫(kù)密碼:
mysqladmin -u root -p password 123456
刪除操作:如果不加過(guò)濾條件就是刪除所有數(shù)據(jù)
delete from 表名 where 列名=列值;
例:delete from students where name='amliu';
刪除所有數(shù)據(jù):
truncate table 表名;
delete與truncate的區(qū)別:
delete可以刪除指定數(shù)據(jù)也能刪除所有數(shù)據(jù)而truncate只能刪除所有數(shù)據(jù)
delete刪除表中數(shù)據(jù),表結(jié)構(gòu)還在刪除后數(shù)據(jù)還可以找回
truncate刪除是把表直接刪除然后創(chuàng)建一個(gè)新表,刪除的數(shù)據(jù)不能找回古程,執(zhí)行速度比delete快
條件查詢:
between...and(值在什么范圍內(nèi))? ? in(set);? ? is null;(為空)? ? is not null;(不為空)? ? and;(與)? ? or;(或)? ? not;(非)
查詢性別為男并且年齡為20的學(xué)生記錄:
select * from students where sex='男' and age=20;
查詢學(xué)號(hào)為1001或者名字為zs的學(xué)生記錄:
select * from students where id=1001 or name='zs';
查詢學(xué)號(hào)為1001,1002,1003的記錄:
select * from students where id in (1001,1002,1003);
模糊查詢:
根據(jù)指定關(guān)鍵字查詢數(shù)據(jù),使用like關(guān)鍵字后跟通配符
_(表示任意一個(gè)字母)? ? %(表示任意0~n個(gè)字母)
查詢姓名由五個(gè)字母構(gòu)成,并且第五個(gè)字母為‘s’的學(xué)生記錄:
select * from students?where name like '____s';
查詢姓名以‘m’開(kāi)頭的學(xué)生記錄:
select * from students where name like 'm%';
使用正則表達(dá)式來(lái)進(jìn)行查詢:
關(guān)鍵字:regexp
基本語(yǔ)法:字段名 regexp '匹配方式'
查名字里面包含z或者s或者l的記錄:
select * from students where name regexp '[zsl]';
查詢姓名中字段以L開(kāi)頭以i結(jié)尾喊崖,并且中間兩個(gè)字符的同學(xué)來(lái)自哪里:
select address from students where name regexp '^L..i$';
去除重復(fù)記錄:
查詢所有學(xué)生name信息挣磨,去除重復(fù)信息:
select distinct name from students;
把查詢字段的結(jié)果進(jìn)行運(yùn)算,必須都要是數(shù)值型:
select *,字段1+字段2 from 表名;(查出所有內(nèi)容荤懂,有添加一個(gè)新的列)
例:select *,age+score from students;
ifnull:把null轉(zhuǎn)化為數(shù)值0
select *茁裙,age+ifnull(score,0) from score;
或者可以將新生成的一列起個(gè)新的名字:
select *,age+ifnull(z_id,0) as total from xuesheng;(其中可以把a(bǔ)s省略掉)
排序(默認(rèn)asc):
關(guān)鍵字:order by
asc(升序)? ? desc(降序)
select * from xuesheng order by age desc,id desc;
將birthday字段的位置改到sex字段面前:
alter table teacher modify birthday datatime after name;
注意:調(diào)換的字段要標(biāo)注上類型节仿,被調(diào)換的可不用標(biāo)注類型
修改存儲(chǔ)引擎
將teacher表的存儲(chǔ)引擎更改為MyISAM類型:
alter table teacher engint=MyISAM;
聚合函數(shù):
count():(統(tǒng)計(jì)指定不為null的記錄行數(shù))
max():(計(jì)算指定列的最大值)
min():(計(jì)算指定列的最小值)
sum():(計(jì)算指定列的數(shù)值和)
avg():(計(jì)算指定列的平均值)