基本的SQL语句包括DQL和DML。即对数据库常用的四大基本操作:查询(Select)、插入(Insert)、更新(Update)、删除(Delete)。 注:db:数据库;xm:姓名;xb:性别;nl:年龄 1、select语句 Select语句语法: select 输出列表 from 表 where 条件 group by 分组依据 having 分组后筛选条件 order by 排序依据 Eg1:select * from db 功能说明:查询db表的所有字段内容 Eg2:select xm,xb from db 功能说明:查询db表的xm,xb字段的内容 Eg3:select * from db where nl>=18 功能说明:查询db表中年龄大于等于18的所有记录 Eg4:select * from db where xm like “王%” 功能说明:查询db表中姓王的所有人员 Eg5:select * from db where xm like “王_” 功能说明:查询db表xm以“王”开头且字数为二的记录 2、insert语句 Insert语句语法: insertinto 表(字段列表) values (值列表) Eg1:insert into db values(“王二”,“男”,“21”) 功能说明:在db表中插入该条记录(如果每个字段都有值,可省略字段列表) Eg2:insert into db(xm,xb) values(“王二”,“男”) 功能说明:在db表中插入该条记录,仅包含xm,xb两个字段 3、update语句 Update语句语法: update 表 set 字段值=新值 where 条件 Eg:update db set nl=“22” where xm=“王二” 功能说明:将db表中xm为“王二”的记录nl改为“22” 4、delete语句 delete from 表 where 条件 Eg:delete from db where xm=“王二” 功能说明:删除db表中xm为“王二”的记录(如果没有where条件,即删除全部记录) 分组函数在实际应用中经常使用,功能是做一些基础的统计和计算。分组函数有5个,分别是sum函数、avg函数、count函数、max函数、min函数。在select语句中,分组函数通常和group by 和having 字句连用,group by 用来设定分组依据,having 设定分组后筛选条件。 注:nl:年龄;db:数据库 1、sum函数:算出某个字段的总值 Eg:select nl,sum(nl) as total from db group by nl 功能说明:查询出所有人年龄的总和 2、avg函数:算出某个字段的平均值 Eg1:select nl,avg(nl) as average from db group by nl 功能说明:查询 出所有人年龄的平均年龄 3、count函数:算出返回记录的行数 4、max函数:算出某个字段的最大值 5、min函数:算出某个字段的最小值 |
|