准备数据:
drop table if exists student;
create table student(
id INT,
sn INT,
name VARCHAR(20),
qq_mail VARCHAR(20)
);
insert into student values(1,1001,'baby','[email protected]');
insert into student values(2,1002,'baby2','[email protected]');
每一行就是一个学生,每一列就是一个学生的某个属性。
对应类来说: 每一行就是一个学生对象,每一列就是一个学生的某个属 性。
insert into student(id,sn,name) values(3,1003,'xx1'),(4,1004,'xx2');
select * from student;
select name from student;
-- 创建考试成绩表
DROP TABLE IF EXISTS exam_result;
CREATE TABLE exam_result (
id INT,
name VARCHAR(20),
chinese DECIMAL(3,1),
math DECIMAL(3,1),
english DECIMAL(3,1)
);
-- 插入测试数据
INSERT INTO exam_result (id,name, chinese, math, english) VALUES
(1,'唐三藏', 67, 98, 56),
(2,'孙悟空', 87.5, 78, 77),
(3,'猪悟能', 88, 98.5, 90),
(4,'曹孟德', 82, 84, 67),
(5,'刘玄德', 55.5, 85, 45),
(6,'孙权', 70, 73, 78.5),
(7,'宋公明', 75, 65, 30);
例子: --查询每个同学的总分
查询总分并且把总分按降序排列
SELECT name, chinese + english + math total FROM exam_result ORDER BY total DESC;
例:–查询同学各门成绩,依次按 数学降序,英语升序,语文 升序的方式显示
SELECT name, math, english, chinese FROM exam_result ORDER BY math DESC, english, chinese;
select distinct math from exam_result;
这样的SQL语句是否也可以去重?
mysql> select id,name, distinct math from exam_result;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘distinct math from exam_result’ at line 1
以上这条语句位置不对!!需要把去重放在第一位!!
mysql> select distinct math, id,name from exam_result;
那么,去重的原理到底是什么?
去重 针对的是所有的字段!!只有当select distinct math, id,name from exam_result;中 的三个字段同时重复的时候,才会去重!!!
将查询结果 按照,根据数学成绩进行从低到高排序的排序
select * from exam_result order by math;
或者:
select * from exam_result order by math asc;
select * from exam_result order by math desc;
desc实际上是一个 关键字
假如你要创建的表名为关键字,一定要加 ``
-- ESC 下面那个键
drop table if exists `desc`;
create table `desc`(
id int,
name varchar(10)
);
insert into exam_result values(8,‘唐三 藏’,67,NULL,80);
从小到大排序
select * from exam_result order by math asc;
从大到小排序
select * from exam_result order by math desc;
1、order by asc 和 order by 默认是从低到高进行排序的
2、order by desc 是从高到第排序的
3、对于MySQL的关键字 ,在用作变量名的时候,一定要 加符号:``
UPDATE table_name SET column = expr [, column = expr …] [WHERE …]
[ORDER BY …] [LIMIT …]
– 将孙悟空同学的数学成绩变更为 80 分
update exam_result set math=80 where name="孙悟空";
– 将曹孟德同学的数学成绩变更为 60 分,语文成绩变更为 70 分
update exam_result set math=60,chinese=70 where name="曹孟德";
– 将总成绩倒数前三的 3 位同学的数学成绩加上 30 分
update exam_result set math = math+30 order by math+english+chinese limit 3;
– 将所有同学的语文成绩更新为原来的 2 倍
update exam_result set chinese=chinese*2 ;
DELETE FROM table_name [WHERE ...] [ORDER BY ...] [LIMIT ...]
– 删除孙悟空同学的考试成绩
delete from exam_result where name="孙悟空";
– 删除整张表数据
– 准备测试表
DROP TABLE IF EXISTS for_delete;
CREATE TABLE for_delete (
id INT,
name VARCHAR(20)
);
– 插入测试数据
INSERT INTO for_delete (name) VALUES ('A'), ('B'), ('C');
– 删除整表数据
DELETE FROM for_delete;
直接删除表:会删除表内所有的数据,但是这张表还是存在的,只不过里面没有数据了!!
delete from exam_result;
drop table exam_result;