一、新增
1.1【插入单行】:insert into <表名> (列名) values (列值)
1.2【将现有表数据添加到一个已有表】:insert into <已有表> (列名) select <原表列名> from <原表名>
例:insert into tongxunlu ('姓名','地址','电子邮件')
select name,address,email
from Strdents
1.3【直接拿现有表数据创建一个新表并填充】:select <新建表列名> into <新建表名> from <源表名>
例:select name,address,email into tongxuelu from strdents
1.4【使用union关键字合并数据进行插入多行】:insert <表名> <列名> select <列值> union select <列值>
例:insert Students (姓名,性别,出生日期)
select '开心朋朋','男','1980/6/15' union
select '蓝色小明','男','19**/**/**'
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
二、删除
2.1【删除<满足条件的>行】:delete from <表名> where <删除条件>
2.2【删除整个表】:truncate table <表名>
使用DROP TABLE 指令会使整个表格就消失,而无法再被用了。
使用 TRUNCATE TABLE 的指令,表格中的资料会完全消失,可是表格本身会继续存在。
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
三、修改
update <表名> set <列名=更新值> where <更新条件>
或者:查询语句后面+for update
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
四、查询
4.1 查询:select <列名> from <表名> where <查询条件表达试>order by <排序的列名>asc或desc
1)可以在查询中使用as更改列名
2)查询空行:用is null或者is not null来判断是否为空行;null值参与运算结果就会为空的
3)模糊查询:like '%关键字%' 主要是针对字符型字段的,它的作用是在一个字符型字段列中检索包含对应子串的
4) 范围内查询:between 条件 and 条件
5)in和exists:外表比内表大使用in,外表比内表小使用exists
6)not in 和 not exists:使用not exists效率会更高 (参考来源:https://www.jianshu.com/p/df614c2c901b)
4.2 select 1 from table
与select * from table 从作用上来说是没有差别的,都是查看是否有记录,一般是作条件查询用的。
select 1 from 中的1是一常量(可以为任意数值),查到的所有行的值都是它,但从效率上来说,1>anycol>*,因为不用查字典表
4.3 查询返回限制行数
例1:select top 6 name from a 查询表a,显示列name的前6行,top为关键字
例2:select top 60 percent name from a 说明:查询表a,显示列name的60%,percent为关键字
例3:select * from a where rownum=10 说明:返回10行,Oracle适用
4.3 使用group by进行分组查询
select studentID as 学员编号,AVG(score) as 平均成绩
from student
group by studentID
说明:按strdentID字段分组,显示strdentID字段和score字段的平均值;select语句中只允许被分组的列和为每个分组返回的一个值的表达式
4.4 使用having子句进行分组筛选
select studentID as 学员编号,AVG(score) as 平均成绩
from student
group by studentID
having count(score)>1
说明:显示分组后count(score)>1的行,由于where只能在没有分组时使用,分组后只能使用having来限制条件。
4.5 多表联接查询
1) 内联接
select a.name,b.chengji from a,b where a.name=b.name
或者: select a.name,b.chengji from a inner join b on (a.name=b.name)
说明: 查询表a和表b中name字段相等的记录,并显示表a中的name字段和表b中的chengji字段
2) 左联接、右联接
LEFT JOIN:即使右表中没有匹配,也从左表返回所有的行
RIGHT JOIN:即使左表中没有匹配,也从右表返回所有的行
select A.*,B.* from A left join B on(A.a1=B.a2)
select A.*,B.* from A right join B on(A.a1=B.a2)