SQL常用命令使用方法:
(1) 数据记录筛选:
sql="select * from 数据表 where 字段名=字段值 order by 字段名 [desc]"
sql="select * from 数据表 where 字段名 like '%字段值%' order by 字段名 [desc]"
sql="select top 10 * from 数据表 where 字段名 order by 字段名 [desc]"
MySQL中,查询前10行数据:sql="select * from 数据表 where 字段名 order by 字段名 [desc] limit 0,10"
sql="select * from 数据表 where 字段名 in ('值1','值2','值3')"
sql="select * from 数据表 where 字段名 between 值1 and 值2"
(2) 更新数据记录:
sql="update 数据表 set 字段名=字段值 where 条件表达式"
sql="update 数据表 set 字段1=值1,字段2=值2 …… 字段n=值n where 条件表达式"
(3) 删除数据记录:
sql="delete from 数据表 where 条件表达式"
sql="delete from 数据表" (将数据表所有记录删除)
(4) 添加数据记录:
sql="insert into 数据表 (字段1,字段2,字段3 …) values (值1,值2,值3 …)"
sql="insert into 目标数据表 select * from 源数据表" (把源数据表的记录添加到目标数据表)
(5) 数据记录统计函数:
AVG(字段名) 得出一个表格栏平均值
COUNT(*¦字段名) 对数据行数的统计或对某一栏有值的数据行数统计
MAX(字段名) 取得一个表格栏最大的值
MIN(字段名) 取得一个表格栏最小的值
SUM(字段名) 把数据栏的值相加
引用以上函数的方法:
sql="select sum(字段名) as 别名 from 数据表 where 条件表达式"
set rs=conn.excute(sql)
用 rs("别名") 获取统的计值,其它函数运用同上。
(6) 数据库 表的创建和删除:
CREATE TABLE 数据表名称(字段1 类型1(长度),字段2 类型2(长度) …… )
例:CREATE TABLE tab01(name varchar(50),datetime default now())

DROP TABLE 数据表名称 (永久性删除一个数据表)
(7)修改基本表
alert table <表名>
[add <新列名> <数据类型> [完整性约束]]
[drop <完整性约束名>]
[modify <列名><数据类型>];
add: 用于向表中增加新列及新列相关的完整性约束条件,新的列增加成功后不带任何数据
drop:用于删除指定的完整性约束条件
modify:用于修改原来的列定义,包括修改列名和数据类型,列数据类型修改后可能会丢失原有的数据

(8)建立与删除索引
create index <索引名> on <表名> (<列名> [<次序][,<列名>[<次序]].....);
注:unique:表明此索引的每个索引值只对应惟一的一个记录
drop index <索引名>;
例如:create unique index studentIndex on student (sno);
drop index studentIndex;
(9)limit的用法
limit被用来限制select返回的行数,如果给定1个参数,它指出返回行的最大数目;如果给定2个参数,第一个指定要返回的第一行的偏移量,第二个指定返回行的最大数目,初始行的偏移量是0
select * from table limit 5;
select * from table limit 5,10;
//选择学生表中所有学生的姓名记录,并且筛选掉重复的记录,将记录保存在名字为name的结果集中,并按学号由大到小排列
select distinct sname as name, sno from student order by snodesc;
//选择学生表中所有学生的姓名和年龄,并将每个同学的姓名后加上“同学”二字,将每个人的年龄增加1岁,同是计算所有同学年龄的平均值
//sum()---- 求所有数据的总和
//max()----求所有数据中的最大值
//min()-----求所有数据中的最小值
//avg()---- 求所有数据的平均值
select sname, "同学", age+1,avg(age) from student;
//列出学号在1和100之间,并且成绩大于85分的所有姓”赵“同学的所有记录;
//%---代表任意字符
//使用通配符时,前面必须用关键字”like”
select * from student where sname like'赵%’ and sno between 1 and 100 and sno in (select sno from student where grade>85);
//使用学生表、课程表以及学生选课表这3个基本表,列出所有学生的姓名、学号、所选课程的课程名称及该课程的学分
select sname, sno, cno, credit from student, course, sc where student.sno = sc.sno and sc.cno = course.cno;
网友评论