创建如下数据表
CREATE TABLE student2(
id INT(10)PRIMARY key ,
name VARCHAR(20)NOT NULL,
sex VARCHAR(4),
birth YEAR,
department VARCHAR(20)NOT NULL,
address VARCHAR(50)
)ENGINE=InnoDB DEFAULT CHARSET=GB2312;
CREATE TABLE score2(
id INT(10)PRIMARY key AUTO_INCREMENT,
stu_id INT(10)NOT NULL,
c_name VARCHAR(20),
grade INT(10),
UNIQUE KEY id (id)
)ENGINE=InnoDB DEFAULT CHARSET=GB2312;
INSERT INTO student2 (id,name,sex,birth,department,address) VALUES
(901,'张老大','男',1985,'计算机系','北京市海淀区'),
(902,'张老二','男',1986,'中文系','北京市昌平区'),
(903,'张三','女',1990,'中文系','湖南省永州市'),
(904,'李四','男',1990,'英语系','辽宁省阜新市'),
(905,'王五','女',1991,'英语系','福建省厦门市'),
(906,'王六','男',1988,'计算机系','湖南省衡阳市');
INSERT INTO score2 (id,stu_id,c_name,grade) VALUES
(NULL,901,'计算机',98),
(NULL,901,'英语',80),
(NULL,902,'计算机',65),
(NULL,902,'中文',88),
(NULL,903,'中文',95),
(NULL,904,'计算机',70),
(NULL,904,'英语',92),
(NULL,905,'英语',94),
(NULL,906,'计算机',90),
(NULL,906,'英语',85);
4.查询student表的第2条到4条记录
SELECT * FROM student2 LIMIT 1,3;
5.从student表查询所有学生的学号(id)、姓名(name)和院系(department)的信息
SELECT id 学号, name 姓名, department 院系 FROM student2;
SELECT * FROM student2 WHERE 2010-birth BETWEEN 18 AND 22;
SELECT department, count(id) FROM student2 GROUP BY department;
SELECT c_name,max(grade) FROM score2 GROUP BY c_name;
10.查询李四的考试科目(c_name)和考试成绩(grade)
SELECT c_name,grade FROM score2 WHERE stu_id=(
SELECT id FROM student2 WHERE name='李四' );
11.用连接的方式查询所有学生的信息和考试信息
SELECT student2.id,student2.name,student2.sex,student2.birth,student2.department, student2.address,score2.c_name,score2.grade
FROM student2,score2 WHERE student2.id=score2.stu_id;
12.计算每个学生的总成绩
SELECT stu_id,sum(grade) FROM score2 GROUP BY stu_id
SELECT c_name,AVG(grade) FROM score2 GROUP BY c_name
SELECT * FROM score2 WHERE c_name='计算机' AND grade<95;
15.查询同时参加计算机和英语考试的学生的信息
SELECT * FROM student2 WHERE id=ANY(
SELECT stu_id FROM score2 WHERE stu_id in
(SELECT stu_id FROM score2 WHERE c_name='计算机') AND c_name='英语');
SELECT * FROM score2 WHERE c_name='计算机' ORDER BY grade DESC
17.从student表和score表中查询出学生的学号,然后合并查询结果
SELECT id FROM student2 UNION all SELECT stu_id FROM score2 ;
18.查询姓张或者姓王的同学的姓名、院系和考试科目及成绩
SELECT student2.name,student2.department,score2.c_name,score2.grade
FROM student2,score2 WHERE student2.id=score2.stu_id AND
( student2.name LIKE '张%' OR student2.name LIKE '王%')
SELECT student2.name,(2010-student2.birth) AS 年龄,student2.department,score2.c_name,score2.grade
FROM student2,score2 WHERE student2.id=score2.stu_id AND
(student2.address LIKE '湖南%')