sql语句—实例及答案
![sql语句—实例及答案](https://img.360docs.net/img5d/02td3vjauq8rbmdwh53j-d1.webp)
![sql语句—实例及答案](https://img.360docs.net/img5d/02td3vjauq8rbmdwh53j-d2.webp)
sql 语句大致可以分类两大类SQL(结构化查询语言)
针对数据库database和表table的操作
创建create
查看show
修改alter
删除drop
// 创建一个数据库
create database mydb;
// 查看所有的数据库库
show databases;
// 删除 mydb
drop database mydb;
// 删除 user 表
drop table user;
针对表中的记录的操作
增 insert
删 delete
改 update
查 select
一、操作数据库
创建一个名称为mydb1的数据库
create database mydb1;
查看当前数据库服务器中的所有数据库
show databases;
删除前面创建的mydb3数据库
drop database mydb3;
二、操作表
1. 创建表
创建员工表
Id 整形
name 字符型
sex 字符型或bit型
brithday 日期型
Entry_date 日期型
job 字符型
Salary 小数型
resume 大文本型
use database mydatabase
create table employee
(
id int,
name varchar(20),
sex varchar(6),
brithday date,
entry_date date,
job varchar(20),
salary double,
resume text
);
2. 修改表
在上面员工表的基础上增加一个image列
alter table employee add colm1 int;
修改job列,使其长度为60
alter table employee modify job varchar(60);
删除sex列。
alter table employee drop sex;
表名改为users。
rename table employee to user;
列名name修改为username
alter table user change column name username varchar(20);
查看所有表
show tables;
删除 user 表
drop table user;
三、数据的增删改查
1. insert语句
create table employee
(
id int primary key,
name varchar(20) not null,
sex varchar(10),
birthday date,
salary float not null,
entry_date date,
resume text
);
// 向员工表插入三条记录
insert into employee(id,name,sex,birthday,salary,entry_date,resume) values(1,'zhangsan','male','1987-11-23',1500,'2010-2-18','good boy'); insert into employee(id,name,sex,birthday,salary,entry_date,resume) values(2,'wangwu','male','1988-11-23',1200,'2010-2-18','good boy'); insert into employee(id,name,sex,birthday,salary,entry_date,resume) values(3,'xiaohong','female','1983-11-23',1800,'2010-2-18','good
girl');
insert into employee(id,name,sex,birthday,salary,entry_date,resume) values(4,'王小明','男','1986-11-23',3800,'2011-2-18','handsome boy');
insert into employee values(5,'王小明','男','1986-11-23',3800,'2011-2-18','handsome boy');
insert into employee(id,name, salary) values(6,'王小明', 3800);
// 查看表的所有记录
select * from employee;
2. update语句
将所有员工薪水修改为5000元
update employee set salary=5000;
将姓名为’zhangsan’的员工薪水修改为3000元。
update employee set salary=3000 where name='zhangsan';
将姓名为’lisi’的员工薪水修改为4000元,sex改为female。
update employee set salary=4000,sex='female' where name='wangwu'; 将xiaohong的薪水在原有基础上增加1000元
update employee set salary=salary+1000 where name='xiaohong';
3. delete语句
删除表中name为’赵楠’的记录。
delete from employee where name='赵楠';
删除表中所有记录。
delete from employee;
4. select语句
student.sql
create table student(
id int,
name varchar(20),
chinese float,
english float,
math float
);
insert into student(id,name,chinese,english,math) values(1,'张小明',89,78,90);
insert into student(id,name,chinese,english,math) values(2,'李进',67,53,95);
insert into student(id,name,chinese,english,math) values(3,'王五',87,78,77);
insert into student(id,name,chinese,english,math) values(4,'李一',88,98,92);
insert into student(id,name,chinese,english,math) values(5,'李来财',82,84,67);
insert into student(id,name,chinese,english,math) values(6,'张进宝',55,85,45);
insert into student(id,name,chinese,english,math) values(7,'黄蓉',75,65,30);
查询表中所有学生的信息。
select * from student;
查询表中所有学生的姓名和对应的英语成绩。
select name,english from student;
过滤表中重复数据。
select distinct english from student;
在所有学生分数上加10分特长分。
select name,english+10,chinese+10,math+10 from student;
统计每个学生的总分。
select name,english+chinese+math as sum from student;
使用别名表示学生分数。
where 子句
查询姓名为李一的学生成绩
select * from student where name='李一';
查询英语成绩大于90分的同学
select * from student where english>90;
查询总分大于200分的所有同学
select name,english+chinese+math from student where
english+chinese+math>200;
运算符
查询英语分数在 80-90之间的同学。
select * from student where english between 65 and 85;
查询数学分数为89,90,91的同学。
select name,math from student where math in(89,90,91);
查询所有姓李的学生成绩。
select * from student where name like '李%';
// 查询姓李的两个字的学生
select * from student where name like '李_';
查询数学分>80,语文分>80的同学。
select * from student where math>80 and chinese>80;
查询英语>80或者总分>200的同学
select *,chinese+math+english from student where english>80 or chinese+english+math>200;
order by 子句
对数学成绩排序后输出。
select * from student order by math;
对总分排序后输出,然后再按从高到低的顺序输出
select *,chinese+math+english from student order by
chinese+math+english desc;
对姓李的学生成绩排序输出
select * from student where name like '李%' order by
chinese+math+english;
合计函数
count
统计一个班级共有多少学生?
select count(*) from student;
统计数学成绩大于90的学生有多少个?
select count(*) from student where math>90;
统计总分大于230的人数有多少?
select count(*) from student where chinese+math+english>230;
sum
统计一个班级数学总成绩?
select sum(math) from student;
统计一个班级语文、英语、数学各科的总成绩
select sum(math),sum(chinese),sum(english) from student;
统计一个班级语文、英语、数学的成绩总和
select sum(math+chinese+english) from student;
统计一个班级语文成绩平均分
select sum(chinese)/count(*) from student;
缺考的不参与计算
select sum(chinese)/count(chinese) from student;
avg
语文平均分
select avg(chinese) from student;
max/min
语文最高分
select max(chinese) from student;
group by
create table orders(
id int,
product varchar(20),
price float
);
insert into orders(id,product,price) values(1,'dianshi',900);
insert into orders(id,product,price) values(2,'xiyiji',100);
insert into orders(id,product,price) values(3,'xiyifen',90);
insert into orders(id,product,price) values(4,'orange',9);
insert into orders(id,product,price) values(5,'xiyifen',90);
将商品归类
select * from orders group by product;
显示单类商品总结
select *,sum(price) from orders group by product;
商品分类显示单类商品总价大于100的
select *,sum(price) from orders group by product having
sum(price)>100;
// 将单价大于20 的商品进行归类显示按照价格排序
select * from orders where price>20 group by product order by price;
四、表的约束
我们可以在创建表的同时为字段增加约束,对将来插入的数据做一些限定
唯一约束 unique
create table a
(
name varchar(20) unique
);
insert into a values('aaa');
insert into a values('aaa'); 错 name有唯一约束
非空约束 not null
create table b
(
id int,
name varchar(20) not null
);
insert into b values(1,'aaa');
insert into b (id) values(2); 错,name有非空约束
主键每张表都应该有个主键方便我们找到记录
主键必须有唯一约束、非空约束
主键约束 primary key
create table c
(
id int primary key,
name varchar(20) not null
);
insert into c (id,name) values(1,'aaaa');
insert into c(id,name) values(1,'bbbb'); 错,主键重复insert into c(name) values('ccc'); 错,主键不能为null
主键可以定义为自动增长,注意主键类型必须是int
create table d
(
id int primary key auto_increment,
name varchar(20)
);
insert into d(name) values('ccc');
insert into d(name) values('aaaa');
delete from d where id=4;
create table e
(
id int,
name varchar(20)
);
// 增加主键约束
alter table e modify id int primary key;
// 删除主键约束
alter table e drop primary key;
// 创建联合主键
create table f
(
firstname varchar(20),
lastname varchar(20),
primary key(firstname, lastname)
);
insert into f values('zhao','nan');
insert into f values('li', 'nan');
最重要的约束外键约束
create table husband
(
id int primary key,
name varchar(20)
);
create table wife
(
id int primary key auto_increment,
name varchar(20),
husbandid int,
constraint husbandid_FK foreign key(husbandid) references husband(id) );
insert into husband (id,name) values(3,'liuxiaoshuai');
insert into wife (name, husbandid) values('fengjie', 3);
delete from husband where id=3;
create table aaa
(
id int
);
// 为aaa 加外键约束
alter table aaa add constraint husid_FK foreign key(id) references husband(id);
// 删除外键约束
alter table aaa drop foreign key husid_FK;
五、对象和表的关系
javabean 一张表
多对一
在多的一方建外键参照一的一方的主键
多对多
需要创建中间表描述关系
中间表需要两列作为联合主键同时又是外键分别参照两张表的主键
一对一
分清主从关系
在从的一方建外键参照主的一方的主键
由于在一对一的关系中外键不允许为空和重复(必须要找到主的一方,否则从的一方就没有存在的意义)
干脆将从的一方的主键直接作为外键
六、多表操作
创建表多表查询
多对一多的一方加外键
create table department
(
id int primary key auto_increment,
name varchar(20)
);
create table employee
(
id int primary key auto_increment,
name varchar(20),
departmentid int,
constraint departmentid_FK foreign key(departmentid) references department(id)
);
// 插入三个部门
insert into department (name) values('开发部');
insert into department (name) values('销售部');
insert into department (name) values('人事部');
// 插入5个员工
insert into employee (name, departmentid) values ('张三', 1);
insert into employee (name, departmentid) values ('王五', 2);
insert into employee (name, departmentid) values ('李四', 3);
insert into employee (name, departmentid) values ('赵六', 2);
insert into employee (name, departmentid) values ('田七', 1);
// 查询
1号部门的员工
select * from employee where departmentid=1;
销售部所有的员工
select id from department where name='销售部';
select * from employee where departmentid=2;
select * from employee where departmentid=(select id from department where name='销售部');
// 多表查询
select * from employee,department;
+----+------+--------------+----+--------+
| id | name | departmentid | id | name |
+----+------+--------------+----+--------+
| 1 | 张三 | 1 | 1 | 开发部 | | 1 | 张三 | 1 | 2 | 销售部 | | 1 | 张三 | 1 | 3 | 人事部 | | 2 | 王五 | 2 | 1 | 开发部 | | 2 | 王五 | 2 | 2 | 销售部 | | 2 | 王五 | 2 | 3 | 人事部 | | 3 | 李四 | 3 | 1 | 开发部 | | 3 | 李四 | 3 | 2 | 销售部 | | 3 | 李四 | 3 | 3 | 人事部 | | 4 | 赵六 | 2 | 1 | 开发部 | | 4 | 赵六 | 2 | 2 | 销售部 | | 4 | 赵六 | 2 | 3 | 人事部 | | 5 | 田七 | 1 | 1 | 开发部 | | 5 | 田七 | 1 | 2 | 销售部 | | 5 | 田七 | 1 | 3 | 人事部 | +----+------+--------------+----+--------+
笛卡尔积
结果中有很多不匹配的数据废数据
去除不匹配数据 (废数据) 一张表的外键列=参照表的主键列select * from employee,department where
employee.departmentid=department.id;
+----+------+--------------+----+--------+
| id | name | departmentid | id | name |
+----+------+--------------+----+--------+
| 1 | 张三 | 1 | 1 | 开发部 | | 5 | 田七 | 1 | 1 | 开发部 | | 2 | 王五 | 2 | 2 | 销售部 | | 4 | 赵六 | 2 | 2 | 销售部 | | 3 | 李四 | 3 | 3 | 人事部 | +----+------+--------------+----+--------+
加上我们的帅选条件
select * from employee,department where
employee.departmentid=department.id and https://www.360docs.net/doc/5116689270.html,='销售部';
最终答案
select e.* from employee e,department d where e.departmentid=d.id and https://www.360docs.net/doc/5116689270.html,='销售部';
多对多
create table teacher
(
id int primary key auto_increment,
name varchar(20)
);
create table student
(
id int primary key auto_increment,
name varchar(20)
);
// 中间表
create table tea_stu
(
teaid int,
stuid int,
primary key(teaid, stuid),
constraint teaid_FK foreign key(teaid) references teacher(id),
constraint stuid_FK foreign key(stuid) references student(id)
);
// 插入三个老师记录
insert into teacher (name) values('老张');
insert into teacher (name) values('老黎');
insert into teacher (name) values('老方');
// 插入7个学生记录
insert into student(name) values('张三');
insert into student(name) values('李四');
insert into student(name) values('王五');
insert into student(name) values('赵楠');
insert into student(name) values('刘小帅');
insert into student(name) values('王芳');
insert into student(name) values('刘红');
// 插入中间表描述关系
insert into tea_stu(teaid, stuid) values(1,1);
insert into tea_stu(teaid, stuid) values(1,2);
insert into tea_stu(teaid, stuid) values(1,3);
insert into tea_stu(teaid, stuid) values(1,4);
insert into tea_stu(teaid, stuid) values(2,3);
insert into tea_stu(teaid, stuid) values(2,4);
insert into tea_stu(teaid, stuid) values(2,5);
insert into tea_stu(teaid, stuid) values(2,7);
insert into tea_stu(teaid, stuid) values(3,2);
insert into tea_stu(teaid, stuid) values(3,4);
insert into tea_stu(teaid, stuid) values(3,1);
insert into tea_stu(teaid, stuid) values(3,5);
insert into tea_stu(teaid, stuid) values(3,6);
// 查询
查询2号老师的学生信息
select s.* from student s, tea_stu ts where s.id=ts.stuid and
ts.teaid=2;
查询老方的所有学生
select s.* from student s, teacher t, tea_stu ts where ts.stuid=s.id and ts.teaid=t.id and https://www.360docs.net/doc/5116689270.html,='老方';
多表查询
n张表联合查需要去掉废数据需要n-1个条件
条件都是外键列=参照列
一对一
create table person
(
id int primary key auto_increment,
name varchar(20)
);
create table idcard
(
id int primary key,
location varchar(20),
constraint personid_FK foreign key(id) references person(id) );
insert into person (name) values('zhangsan');
insert into person (name) values('lisi');
insert into idcard (id,location) values(2,'天津');
insert into idcard (id,location) values(1,'上海');
查李四的身份证
select idcard.* from person,idcard where idcard.id=person.id and https://www.360docs.net/doc/5116689270.html,='lisi';
常用SQL语句大全
常用SQL语句大全 一、基础 1、说明:创建数据库 CREATE DATABASE database-name 2、说明:删除数据库 DROP database dbname 3、说明:备份sql server --- 创建备份数据的device USE master EXEC sp_addumpdevice 'disk', 'testBack', 'c:\mssql7backup\MyNwind_1.dat' --- 开始备份 BACKUP DATABASE pubs TO testBack 4、说明:创建新表 create table tabname(col1 type1 [not null] [primary key],col2 type2 [not null],..) 根据已有的表创建新表: A:create table tab_new like tab_old (使用旧表创建新表) B:create table tab_new as select col1,col2…from tab_old definition only 5、说明:删除新表 DROP table tabname 6、说明:增加一个列 Alter table tabname add column col type 注:列增加后将不能删除。DB2中列加上后数据类型也不能改变,唯一能改变的是增加varchar类型的长度。 7、说明:添加主键:Alter table tabname add primary key(col) 说明:删除主键:Alter table tabname DROP primary key(col) 8、说明:创建索引:create [unique] index idxname on tabname(col….) 删除索引:DROP index idxname 注:索引是不可更改的,想更改必须删除重新建。 9、说明:创建视图:create view viewname as select statement 删除视图:DROP view viewname 10、说明:几个简单的基本的sql语句 选择:select * from table1 where 范围 插入:insert into table1(field1,field2) values(value1,value2) 删除:delete from table1 where 范围 更新:update table1 set field1=value1 where 范围 查找:select * from table1 where field1 like ’%value1%’---like的语法很精妙,查资料! 排序:select * from table1 order by field1,field2 [desc] 总数:select count as totalcount from table1 求和:select sum(field1) as sumvalue from table1 平均:select avg(field1) as avgvalue from table1 最大:select max(field1) as maxvalue from table1 最小:select min(field1) as minvalue from table1 11、说明:几个高级查询运算词
SQL常用语法及例子精简——快速入手
sql语言 库表的增删改查常用语及语法 (1)数据记录筛选: sql="select*from 数据表where 字段名=字段值orderby字段名[desc]" sql="select*from 数据表where 字段名like'%字段值%'orderby字段名[desc]" sql="selecttop10*from 数据表where 字段名orderby字段名[desc]" sql="select*from 数据表where 字段名in('值1','值2','值3')" sql="select*from 数据表where 字段名between 值1and 值2" (2)更新数据记录: sql="update 数据表set 字段名=字段值where 条件表达式" sql="update 数据表set 字段1=值1,字段2=值2……字段n=值nwhere条件表达式" (3)删除数据记录: sql="de letefrom数据表where 条件表达式" sql="de letefrom数据表"(将数据表所有记录删除) (4)添加数据记录: sql="insertinto数据表(字段1,字段2,字段3…)values(值1,值2,值3…)" sql="insertinto目标数据表select*from 源数据表"(把源数据表的记录添加到目标数据表) (5)数据记录统计函数: AVG(字段名)得出一个表格栏平均值 COUNT(*|字段名)对数据行数的统计或对某一栏有值的数据行数统计 MAX(字段名)取得一个表格栏最大的值 MIN(字段名)取得一个表格栏最小的值 SUM(字段名)把数据栏的值相加 引用以上函数的方法: sql="selectsum(字段名)as 别名from 数据表where 条件表达式" setrs=conn.excute(sql) 用rs("别名")获取统的计值,其它函数运用同上。 (6)数据表的建立和删除: CREATETABLE 数据表名称(字段1 类型1(长度),字段2 类型2(长度)……) 例:CREATETABLEtab01 (namevarchar (50), datetimedefaultnow ()) DROPTABLE 数据表名称(永久性删除一个数据表) 4.记录集对象的方法: rs.movenext将记录指针从当前的位置向下移一行 rs.moveprevious将记录指针从当前的位置向上移一行 rs.movefirst将记录指针移到数据表第一行 rs.movelast将记录指针移到数据表最后一行 rs.absoluteposition=N 将记录指针移到数据表第N 行 rs.absolutepage=N 将记录指针移到第N 页的第一行 rs.pagesize=N 设置每页为N 条记录 rs.pagecount根据pagesize的设置返回总页数 rs.recordcount返回记录总数 rs.bof返回记录指针是否超出数据表首端,true 表示是,false 为否
SQL语句实例
表操作 例1 对于表的教学管理数据库中的表STUDENTS,可以定义如下:CREATE TABLE STUDENTS, ( SNO NUMERIC (6, 0) NOT NULL, SNAME CHAR (8) NOT NULL, AGE NUMERIC(3,0), SEX CHAR(2), BPLACE CHAR(20), PRIMARY KEY(SNO) ) 例2 对于表的教学管理数据库中的表ENROLLS,可以定义如下:CREATE TABLE ENROLLS ( SNO NUMERIC(6,0) NOT NULL, CNO CHAR(4) NOT NULL, GRADE INT, PRIMARY KEY(SNO,CNO), FOREIGN KEY(SNO) REFERENCES STUDENTS(SNO), FOREIGN KEY(CNO) REFERENCES COURSES(CNO), CHECK ((GRADE IS NULL) OR (GRADE BETWEEN 0 AND 100)) ) 例3 根据表的STUDENTS 表,建立一个只包含学号、姓名、年龄的女学生表。CREATE TABLE GIRL AS SELECT SNO, SNAME, AGE FROM STUDENTS WHERE SEX='女'; 例4 删除教师表TEACHER。 DROP TABLE TEACHER 例5 在教师表中增加住址列。 ALTER TABLE TEACHERS ADD (ADDR CHAR(50))
例6 把STUDENTS表中的BPLACE列删除,并且把引用BPLACE列的所有视图和约束也一起删除。 ALTER TABLE STUDENTS DROP BPLACE CASCADE 例7 补充定义ENROLLS表的主关键字。 ALTER TABLE ENROLLS ADD PRIMARY KEY (SNO,CNO); 视图操作(虚表) 例9 建立一个只包括教师号、姓名和年龄的视图FACULTY。(在视图定义中不能包含ORDER BY子句) CREATE VIEW FACULTY AS SELECT TNO, TNAME, AGE FROM TEACHERS 例10 从学生表、课程表和选课表中产生一个视图GRADE_TABLE,它包括学生姓名、课程名和成绩。 CREATE VIEW GRADE_TABLE AS SELECT SNAME,CNAME,GRADE FROM STUDENTS,COURSES,ENROLLS WHERE STUDENTS.SNO=ENROLLS.SNO AND https://www.360docs.net/doc/5116689270.html,O=https://www.360docs.net/doc/5116689270.html,O 例11 删除视图GRADE_TABLE DROP VIEW GRADE_TABLE RESTRICT 索引操作 例12 在学生表中按学号建立索引。 CREATE UNIQUE INDEX ST ON STUDENTS (SNO,ASC) 例13 删除按学号所建立的索引。 DROP INDEX ST 数据库模式操作 例14 创建一个简易教学数据库的数据库模式TEACHING_DB,属主为ZHANG。 CREATE SCHEMA TEACHING_DB AUTHRIZATION ZHANG 例15 删除简易教学数据库模式TEACHING_DB。((1)选用CASCADE,即当删除数据库模式时,则本数据库模式和其下属的基本表、视图、索引等全
SQL语句大全实例
SQL语句实例 表操作 例 1 对于表的教学管理数据库中的表STUDENTS ,可以定义如下:CREATE TABLE STUDENTS (SNO NUMERIC (6, 0) NOT NULL SNAME CHAR (8) NOT NULL AGE NUMERIC(3,0) SEX CHAR(2) BPLACE CHAR(20) PRIMARY KEY(SNO)) 例 2 对于表的教学管理数据库中的表ENROLLS ,可以定义如下: CREATE TABLE ENROLLS (SNO NUMERIC(6,0) NOT NULL CNO CHAR(4) NOT NULL GRADE INT PRIMARY KEY(SNO,CNO) FOREIGN KEY(SNO) REFERENCES STUDENTS(SNO) FOREIGN KEY(CNO) REFERENCES COURSES(CNO) CHECK ((GRADE IS NULL) OR (GRADE BETWEEN 0 AND 100))) 例 3 根据表的STUDENTS 表,建立一个只包含学号、姓名、年龄的女学生表。 CREATE TABLE GIRL
AS SELECT SNO, SNAME, AGE FROM STUDENTS WHERE SEX=' 女'; 例 4 删除教师表TEACHER 。 DROP TABLE TEACHER 例 5 在教师表中增加住址列。 ALTER TABLE TEACHERS ADD (ADDR CHAR(50)) 例 6 把STUDENTS 表中的BPLACE 列删除,并且把引用BPLACE 列的所有视图和约束也一起删除。 ALTER TABLE STUDENTS DROP BPLACE CASCADE 例7 补充定义ENROLLS 表的主关键字。 ALTER TABLE ENROLLS ADD PRIMARY KEY (SNO,CNO) ; 视图操作(虚表) 例9 建立一个只包括教师号、姓名和年龄的视图FACULTY 。( 在视图定义中不能包含ORDER BY 子句) CREATE VIEW FACULTY AS SELECT TNO, TNAME, AGE FROM TEACHERS 例10 从学生表、课程表和选课表中产生一个视图GRADE_TABLE ,它包括学生姓名、课程名和成绩。 CREATE VIEW GRADE_TABLE AS SELECT SNAME,CNAME,GRADE FROM STUDENTS,COURSES,ENROLLS WHERE STUDENTS.SNO =ENROLLS.SNO AND https://www.360docs.net/doc/5116689270.html,O=https://www.360docs.net/doc/5116689270.html,O 例11 删除视图GRADE_TABLE DROP VIEW GRADE_TABLE RESTRICT 索引操作 例12 在学生表中按学号建立索引。 CREATE UNIQUE INDEX ST ON STUDENTS (SNO,ASC) 例13 删除按学号所建立的索引。 DROP INDEX ST 数据库模式操作
SQL常用语句+举例
SQL 常用语句+举例 相关表: 1. distinct: 剔除重复记录 例:select distinct stroe_name from Store_information 结果: 2. And / or: 并且/或 例:在表中选出所有sales 高于$1000或是sales 在$275及$500之间的记录 Select store_name ,sales from Store_information Where sales>1000 Or (sales>275 and sales <500) 3. 例:在表中查找store_name 包含 Los Angeles 或San Diego 的记录 Select * from Store_information where store_name in (‘Los Angeles ’,’San Diego ’) 结果: 4. Between : 可以运用一个范围抓出表中的值
与in 的区别:in 依照一个或数个不连续的值的限制抓出表中的值 例:查找表中介于Jan-06-1999 及Jan-10-1999 中的记录 Select * from Store_information where date between ‘Jan-06-1999’ and ‘Jan-10-1999’ 结果: 5. Like : 让我们依据一个套式来找出我们要的记录 套式通常包含: ’A_Z ’: 所有以A 开头,中间包含一个字符,以Z 结尾的字串 ’ABC%’: 所有以ABC 起头的字串 ’%XYZ ’: 所有以XYZ 结尾的字串 ’%AN%’: 所有包含AN 的字串 例:Select * from Store_information where store_name like ‘%An%’ 结果: 6. Order by: 排序,通常与ASC (从小到大,升序)、DESC (从大到小,降序)结合使用 当排序字段不止一个时,先依据字段1排序,当字段1有几个值相同时,再依据字段2排序 例:表中sales 由大到小列出Store_information 的所有记录 Select Store_name, sales,date from Store_information order by sales desc 结果: 7. 函数:AVG (平均值)、COUNT (计数)、MAX (最大值)、MIN (最小值)、SUM(求和) 语句:select 函数名(字段名) from 表名 例:求出sales 的总和 Select sum(sales) from Store_information 结果 8. COUNT (计数) 例:找出Store_information 表中 有几个store_name 值不是空的记录
50个常用sql语句实例(学生表 课程表 成绩表 教师表)
Student(S#,Sname,Sage,Ssex) 学生表 Course(C#,Cname,T#) 课程表 SC(S#,C#,score) 成绩表 Teacher(T#,Tname) 教师表 create table Student(S# varchar(20),Sname varchar(10),Sage int,Ssex varchar(2)) 前面加一列序号: if exists(select table_name from information_schema.tables where table_name='Temp_Table') drop table Temp_Table go select 排名=identity(int,1,1),* INTO Temp_Table from Student go select * from Temp_Table go drop database [ ] --删除空的没有名字的数据库 问题: 1、查询“”课程比“”课程成绩高的所有学生的学号; select a.S# from (select s#,score from SC where C#='001') a,(select s#,score from SC where C#='002') b where a.score>b.score and a.s#=b.s#; 2、查询平均成绩大于分的同学的学号和平均成绩; select S#,avg(score) from sc group by S# having avg(score) >60; 3、查询所有同学的学号、姓名、选课数、总成绩; select Student.S#,Student.Sname,count(SC.C#),sum(score) from Student left Outer join SC on Student.S#=SC.S# group by Student.S#,Sname 4、查询姓“李”的老师的个数; select count(distinct(Tname)) from Teacher where Tname like '李%'; 5、查询没学过“叶平”老师课的同学的学号、姓名; select Student.S#,Student.Sname from Student
SQL查询语句例子
数据表的查询(select) select 字段列表[as 别名], * from 数据表名 [where 条件语句] [group by 分组字段] [order by 排序字段列表desc] [LIMIT startrow,rownumber] 1、Select 字段列表From 数据表 例:①、select id,gsmc,add,tel from haf (* 表示数据表中所有字段) ②、select 单价,数量,单价*数量as 合计金额from haf (As 设置字段的别名) 2、Select …from …Where 筛选条件式 筛选条件式:①、字符串数据:select * from 成绩单Where 姓名='李明' ②、万用字符:select * from 成绩单Where 姓名like '李%' select * from 成绩单Where 姓名like '%李%' select * from 成绩单Where 姓名like '%李_' ③、特殊的条件式: ⑴= / > / < / <> / >= / <= ⑵AND(逻辑与) OR(逻辑或) NOT(逻辑非) ⑶Where 字段名称in(值一,值二) ⑷Where 字段名称Is Null / Where 字段名称Is Not Null 3、Select …from …group by 字段 SQL函数: SELECT sex,count(id) as women from `user` group by 'sex'; 函数名描述函数名描述 AVG平均值Count计数 MAX最大值MIN最小值 Sum求和
sql基础语句
掌握SQL四条最基本的数据操作语句:Insert,Select,Update和Delete。 练掌握SQL是数据库用户的宝贵财富。在本文中,我们将引导你掌握四条最基本的数据操作语句—SQL的核心功能—来依次介绍比较操作符、选择断言以及三值逻辑。当你完成这些学习后,显然你已经开始算是精通SQL了。 在我们开始之前,先使用CREATE TABLE语句来创建一个表(如图1所示)。DDL语句对数据库对象如表、列和视进行定义。它们并不对表中的行进行处理,这是因为DDL语句并不处理数据库中实际的数据。这些工作由另一类SQL语句—数据操作语言(DML)语句进行处理。 SQL中有四种基本的DML操作:INSERT,SELECT,UPDA TE和DELETE。由于这是大多数SQL用户经常用到的,我们有必要在此对它们进行一一说明。在图1中我们给出了一个名为EMPLOYEES的表。其中的每一行对应一个特定的雇员记录。请熟悉这张表,我们在后面的例子中将要用到它。 INSERT语句 用户可以用INSERT语句将一行记录插入到指定的一个表中。例如,要将雇员John Smith的记录插入到本例的表中,可以使用如下语句: INSERT INTO EMPLOYEES V ALUES ('Smith','John','1980-06-10', 'Los Angles',16,45000); 通过这样的INSERT语句,系统将试着将这些值填入到相应的列中。这些列按照我们创建表时定义的顺序排列。在本例中,第一个值“Smith”将填到第一个列LAST_NAME中;第二个值“John”将填到第二列FIRST_NAME中……以此类推。 我们说过系统会“试着”将值填入,除了执行规则之外它还要进行类型检查。如果类型不符(如将一个字符串填入到类型为数字的列中),系统将拒绝这一次操作并返回一个错误信息。 如果SQL拒绝了你所填入的一列值,语句中其他各列的值也不会填入。这是因为SQL提供对事务的支持。一次事务将数据库从一种一致性转移到另一种一致性。如果事务的某一部分失败,则整个事务都会失败,系统将会被恢复(或称之为回退)到此事务之前的状态。 回到原来的INSERT的例子,请注意所有的整形十进制数都不需要用单引号引起来,而字符串和日期类型的值都要用单引号来区别。为了增加可读性而在数字间插入逗号将会引起错误。记住,在SQL中逗号是元素的分隔符。 同样要注意输入文字值时要使用单引号。双引号用来封装限界标识符。 对于日期类型,我们必须使用SQL标准日期格式(yyyy-mm-dd),但是在系统中可以进行定义,以接受其他的格式。当然,2000年临近,请你最好还是使用四位来表示年份。
50个常用的SQL语句练习
基本信息Student(`S#`,Sname,Sage,Ssex) 学生表 Course(`C#`,Cname,`T#`) 课程表 SC(`S#`,`C#`,score) 成绩表 Teacher(`T#`,Tname) 教师表 问题: 1、查询“001”课程比“002”课程成绩高的所有学生的学号; select a.`S#` from (select `S#`,score from SC where `C#`='001') a,(select `S#`,score from SC where `C#`='002') b where a.score>b.score and a.`S#`=b.`S#`; ↑一张表中存在多对多情况的 2、查询平均成绩大于60分的同学的学号和平均成绩; 答案一:select `S#`,avg(score) from sc group by `S#` having avg(score) >60; ↑一对多,对组进行筛选 答案二:SELECT s ,scr FROM (SELECT sc.`S#` s,AVG(sc.`score`) scr FROM sc GROUP BY sc.`S#`) rs WHERE rs.scr>60 ORDER BY rs.scr DESC ↑嵌套查询可能影响效率 3、查询所有同学的学号、姓名、选课数、总成绩; 答案一:select Student.`S#`,Student.Sname,count(`C#`),sum(score) from Student left Outer join SC on Student.`S#`=SC.`S#` group by Student.`S#`,Sname ↑如果学生没有选课,仍然能查出,显示总分null(边界情况) 答案二:SELECT student.`S#`,student.`Sname`,COUNT(sc.`score`) 选课数,SUM(sc.`score`) 总分FROM Student,sc WHERE student.`S#`=sc.`S#` GROUP BY sc.`S#` ↑如果学生没有选课,sc表中没有他的学号,就查不出该学生,有缺陷! 4、查询姓“李”的老师的个数; select count(distinct(Tname)) from Teacher where Tname like '李%'; 5、查询没学过“叶平”老师课的同学的学号、姓名; select Student.`S#`,Student.Sname from Student where `S#` not in (select distinct(SC.`S#`) from SC,Course,Teacher where SC.`C#`=Course.`C#` and Teacher.`T#`=Course.`T#` and Teacher.Tname='叶平'); ↑反面思考Step1:先找学过叶平老师课的学生学号,三表联合查询 Step2:在用not in 选出没学过的 Step3:distinct以防叶平老师教多节课;否则若某同学的几节课都由叶平教,学号就会出现重复 6、查询学过“001”并且也学过编号“002”课程的同学的学号、姓名; select Student.`S#`,Student.Sname from Student,SC where Student.`S#`=SC.`S#` and SC.`C#`='001'and exists( Select * from SC as SC_2 where SC_2.`S#`=SC.`S#` and SC_2.`C#`='002' ); ↑注意目标字段`S#`关联 exists subquery 可以用in subquery代替,如下 select Student.`S#`,Student.Sname from Student,Sc where Student.`S#`=SC.`S#` and SC.`C#`='001'and sc.`s#` in ( select sc_2.`s#` from sc as sc_2 where sc_2.`c#`='002' ); ↑不同之处,in subquery此处就不需要关联了
sql常用语句100例
--update phoneinfo set cityname = '克孜勒苏柯尔克孜' where cityname = '克孜勒苏柯尔克孜州' --update phoneinfo set cityname = '湘西' where pad1 = '湖南 吉首' select * from dbo.PhoneInfo --update dbo.PhoneInfo set provincename=b.provincename,cityname=b.cityname from dbo.PhoneInfo a,PhoneInfo_hl b --where a.phonebound=b.phonebound --select * from dbo.UnknowPhoneBound --select * from dbo.Area --select * from phoneinfo a, phoneinfo_old b, phoneinfo_hl c where a.phonebound = b.phonebound and a.phonebound = c.phonebound and (a.cityname <> b.cityname or a.cityname <> c.cityname) --select * from phoneinfo a, phoneinfo_hl b where a.phonebound = b.phonebound and a.cityname <> b.citynameselect * from phoneinfo a, phoneinfo_old b where a.phonebound = b.phonebound and a.cityname <> b.cityname --select * into phoneinfo_bak from phoneinfo --select * from phoneinfo_bak select * from phoneinfo a, phoneinfo_old b where a.phonebound = b.phonebound and a.cityname <> b.cityname --select * from dbo.PhoneInfo_Telecom --update PhoneInfo_Telecom set provincename = '内蒙古' where pad1 = '内蒙兴安盟' update PhoneInfo set cityname = '酒泉' where pad1 = '甘肃 酒泉嘉峪关' --update dbo.PhoneInfo_old set provincename=b.provincename,cityname=b.cityname from dbo.PhoneInfo_old a,PhoneInfo_Telecom b --where a.phonebound=b.phonebound create table client_all as
sql常用语句
iBATIS常用Sql语句 版本1.0
文档修订记录 版本编号或者更改记录编号*变化 状态 简要说明(变更内容和变更范 围) 日期变更人审核日期审核人 1.0 新建2009-4-17 谷涛 1.1 增加2009-4-28 谷涛*变化状态:A——增加,M——修改,D——删除
(1) 输入参数为单个值