1.MySQL的表数据类型
整数:int,bit
小数:decimal 表示浮点数,如decimal(5,2)表示共存5位数,小数占2位。
字符串:varchar,char char表示固定长度的字符串,如char(3),如果填充’ab’时会补一个空格为’ab ’
varchar表示可变长度的字符串,如varchar(3),填充’ab’时就会存储’ab’。
日期时间: date, time, datetime
枚举类型(enum)
2.用SQL语句创建表 设定列类型、大小、约束、设定主键
create table student (id int primary key,name vachar(20) not null );
3.用SQL 语句像表中添加数据,多种添加方式(指定列名,不指定列名)
insert into student values (1,“zhangsan”);
insert into student (id ,name) values(8,‘吕布’),(9.‘貂蝉’);
4.用SQL 语句删除表
删除数据
delete from student where id = 7;
删除表
drop table hero;
5.用sql 修改下列语句:
修改列名
alter table student change name student_name varchar(20);
修改表中数据
update student set english = 50 where id =7;
删除行
alter table student drop id;
删除列
delete from student where id =7;
新建列
alter table student add age int;
新建行
insert into student (id,name) values(2,‘zhangsan’);
作业
超过5名学生的课(难度:简单)
创建如下所示的courses 表 ,有: student (学生) 和 class (课程)。
例如,表:
±--------±-----------+
| student | class |
±--------±-----------+
| A | Math |
| B | English |
| C | Math |
| D | Biology |
| E | Math |
| F | Computer |
| G | Math |
| H | Math |
| I | Math |
| A | Math |
±--------±-----------+
create table courses (
student varchar(20),
class varchar(20)
)engine=Innodb charset=utf8;
insert into courses values(‘A’,‘Math’),(‘B’,‘English’),(‘C’,‘Math’),(‘D’,‘Biology’),(‘E’,‘Math’),(‘F’,‘Computer’),(‘G’,‘Math’),(‘H’,‘Math’),
(‘I’,‘Math’),(‘A’,‘Math’);
编写一个 SQL 查询,列出所有超过或等于5名学生的课。
select class from courses group by class having count(class)>=5;
select class from (select class ,count()as total from courses group by class)as A where A.total>=5;
1.select class ,count()as total from courses group by class
将课程分组,查询并记录每门课程出现的次数
2. 将子查询的结果作为A 从A中查询课程出现次数大于等于5 的课程
select class from (子查询)as A where A.total>=5;
应该输出:
±--------+
| class |
±--------+
| Math |
±--------+
Note:
学生在每个课中不应被重复计算。
select distinct student,class from courses;
结果:
A Math
B English
C Math
D Biology
E Math
F Computer
G Math
H Math
I Math
交换工资(难度:简单)
创建一个 salary表,如下所示,有m=男性 和 f=女性的值 。
例如:
id | name | sex | salary |
---|---|---|---|
1 | A | m | 2500 |
2 | B | f | 1500 |
3 | C | m | 5500 |
4 | D | f | 500 |
create table salary (
id int primary key auto_increment,
name varchar(20),
sex varchar(2),
salary int
)engine=Innodb charset=utf8;
insert into salary values(1,‘A’,‘m’,2500),(2,‘B’,‘f’,1500),(3,‘C’,‘m’,5500),(4,‘D’,‘f’,500);
交换所有的 f 和 m 值(例如,将所有 f 值更改为 m,反之亦然)。要求使用一个更新查询,并且没有中间临时表。
运行你所编写的查询语句之后,将会得到以下表:
id | name | sex | salary |
---|---|---|---|
1 | A | f | 2500 |
2 | B | m | 1500 |
3 | C | f | 5500 |
4 | D | m | 500 |
update salary
set sex = case sex when ‘m’ then ‘f’ when ‘f’ then ‘m’ end;
select * from salary;