常用SQL语句

本课程主要内容概要

  1. C(insert) 插入/创建语句
  2. U(update) 更新语句
  3. R(select) 查询语句
  4. D(delete) 删除语句
  5. 数据记录统计函数

1.C(insert) 插入/创建语句

insert into 数据表 (字段1,字段2,字段3 …) values (值1,值2,值3 …)
insert into 目标数据表 select * from 源数据表" (把源数据表的记录添加到目标数据表)

2.U(update) 更新语句

update 数据表 set 字段名=字段值 where 条件表达式
update 数据表 set 字段1=值1,字段2=值2 …… 字段n=值n where 条件表达式

3. R(select) 查询语句

先介绍一下通配符

  1. %:代表任意多个字符 name LIKE '李%'
  2. _(下划线):代表任意一个字符
  3. []:指定范围的一个字符,如: sex like '[男女]' id like [0-9][0-9]
  4. IN:限制范围 id in(0,1,2,3,4,5,6,7,8,9)
  5. :不在指定范围里的一个字符
  6. age>=0 and age<=100 age between 0 and 100
select * from 数据表
例:select * from user where id=1

select * from 数据表 where 字段名=字段值 order by 字段名 desc
select * from 数据表 where 字段名 like ‘%字段值%‘ order by 字段名 asc
select * from 数据表 where 字段名 in (‘值1‘,‘值2‘,‘值3‘)
select * from 数据表 where 字段名 between1 and2

4.D(delete) 删除语句

delete from 数据表 where 条件表达式
delete from 数据表" (将数据表所有记录删除)

5.数据记录统计函数

AVG(字段名) 得出一个表格栏平均值
COUNT(*|字段名) 对数据行数的统计或对某一栏有值的数据行数统计
MAX(字段名) 取得一个表格栏最大的值
MIN(字段名) 取得一个表格栏最小的值
SUM(字段名) 把数据栏的值相加

引用以上函数的方法:

sql="select sum(字段名) as 别名 from 数据表 where 条件表达式"

6.数据表的建立和删除:

CREATE TABLE 数据表名称(字段1 类型1(长度),字段2 类型2(长度) …… )
例:CREATE TABLE tab01(name varchar(50),datetime default now())

DROP TABLE 数据表名称 (永久性删除一个数据表)