Datawhale-Mysql 数据库基础练习(2)

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=女性的值 。
例如:

idnamesexsalary
1Am2500
2Bf1500
3Cm5500
4Df500

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,反之亦然)。要求使用一个更新查询,并且没有中间临时表。
运行你所编写的查询语句之后,将会得到以下表:

idnamesexsalary
1Af2500
2Bm1500
3Cf5500
4Dm500

update salary
set sex = case sex when ‘m’ then ‘f’ when ‘f’ then ‘m’ end;

select * from salary;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值