SQL基础 二
关键词: SQL , INSERT,UPDATE,DELETE
经过前面的学习,你是否对关系型数据库有所了解呢?今天我将继续介绍SQL的命令类型。
3.2 数据操作语言(DML)
数据操作语言使数据库用户能够对关系型数据库里的数据进行修改,包括用新数据填充表、更新现有表里的数据、删除表里的数据。
将数据插入到表
insert into table_name values('value1','value2',[null]);
例:插入学号为1102,姓名为binge,班级为1203的数据。
insert into stuinfo values('1102','binge',1203);
注意:Values里包含表里的每个列,都必须有值(除非该字段可为空,但仍要在该字段响应的位置写null),顺序应与列表里的顺序一致,每个值之间由逗号隔开,字符、日期和时间类型的值必须以单引号包围,数值或null不用!!
向表里指定列插入数据
insert into table_name(filed1,filed2,...) values('value1','value2',...);
例:插入学号为1103,姓名为xiaokedou的数据。
insert into stuinfo(id,name) values('1103','xiaokedou');
注意:filed1、filed2必须与表里的字段名一致,顺序没有硬性规定,values的值,应与filed1、filed2相对应。不为空的字段必须添加,除非有自增属性!!
根据对A数据库的查询结果把数据插入到表B里
insert into table_name [(filed1,filed2)]//[ ]里的内容可有可无,如果有则表示插入指定列,否则表示插入全部。
select[ * | (filed1 , filed2) ] //根据上面的写法,选择相应的写法。
from table_name
[ where condition(s) ] //选择条件,根据实际情况是否要写。
例:将湖南工业大学15年新生学生信息,添加到教育局系统中。
insert into eduinfo (schoolid,stuid,stuname)
select schoolid,stuid,stuname
from stuinfo,schoolinfo
where year = 2015 and schoolname='湖南工业大学'
注意:数据库A要添加的value与数据库B要查询的value,属性要一 一对应,而且数据库A的不为空的字段必须要有,除非有自增属性。
更新一列数据
update table_name set filed = 'value'[ where condition ] //filed为字段名,table_name为表名,[]内容要根据需求来,若更新整整一列则不写。
例:初始化所有用户的密码为123
update info set psw = '123';
更新一条或多条字段
update table_name
set column1 = 'value'
[ column2 = 'value' ]
[ column3 = 'value' ]
[where codition];
例:设置15级新生的登陆教务系统的密码为123和学历为本科
update stuinfo
set pwd = '123'
xueli = '本科'
where year = 2015
删除数据
利用DELETE命令用于从表里删除整行数据。他不能删除某一列数据,而是删除一行的全部数据。使用DELETE语句一定要谨慎,不要省略where语句,如果没有where子句,将会删除表里的所有数据,故一定要谨慎!!!
delete from table_name
where condition;
注意!!!!一定不要忘记where语句!
例:删除2010年毕业的全部学生的信息。
delete from stuinfo
where year+nianzhi = 2010; //year表示入学年,nianzhi表示年制
尊重原创,写博不易,转载请注