Mysql练习遇到的问题
参考链接:
https://www.runoob.com/w3cnote/sql-syntax-manual.html.
1.每一行mysql代码一定要写;
1.创建Student表
(1)分步骤写
①先写一个Sno属性
CREATE TABLE Student(Sno varchar(20) not null );
②想为Sno属性添加主键
ALTER TABLE Student ADD PRIMARY KEY(Sno);
③为已经创建好的表中添加字段(属性)
ALTER TABLE Student add Ssex varchar(20) not null ;
④向表中所有字段插入数据
insert into Student values(‘108’,‘曾华’,‘男’,‘1977-09-01’,95033);
⑤为表中指定字段添加数据
insert into Student (Sno,Sname,Ssex) values(‘105’,‘匡明’,‘男’);
2.直接创建Student表
(1)设计表结构
create table student
(
sno varchar(20) not null primary key,
sname varchar(20) not null,
ssex varchar(20) not null,
sbirthday datetime,
class varchar(20)
);
(2)直接向表中添加数据
insert into student values(‘108’,‘曾华’,‘男’,‘1977-09-01’,‘95033’);
insert into student values(‘105’,‘匡明’,‘男’,‘1975-10-02’,‘95031’);
insert into student values(‘107’,‘王丽’,‘女’,‘1976-01-23’,‘95033’);
insert into student values(‘101’,‘李军’,‘男’,‘1976-02-20’,‘95033’);
insert into student values(‘109’,‘王芳’,‘女’,‘1975-02-10’,‘95031’);
insert into student values(‘103’,‘陆君’,‘男’,‘1974-06-03’,‘95031’);
常见操作(参照上图)
1.查找去重后的数据
在表中,一个列可能会包含多个重复值,有时您也许希望仅仅列出不同(distinct)的值。
DISTINCT 关键词用于返回唯一不同的值。
例:查询教师所有的单位即不重复的Depart列。
select distinct Depart from teacher;
2.查询所有数据
select * from 表名
例:
select * from student;
- 查询Score表中成绩在60到80之间的所有记录。
select * from Score where Degree between60and 80
- 查询Score表中成绩为85,86或88的记录。
select * from Score where Degree in(85,86,88);
5.查询Student表中“95031”班或性别为“女”的同学记录。
select * from Student where class='95031’orSsex=‘女’;
6.排序操作
Order by
用途:
指定结果集的排序。
语法:
SELECT column-name(s) FROM table-name ORDER BY { order_by_expression [ ASC | DESC ] }
注:
DESC为降序排序(递减方式排序,从最高值到最低值),ASC为升序排序(递增方式排序,从最低值到最高值)
例:
①以Class降序查询Student表的所有记录。
select * from student order by class desc;
②以Cno升序、Degree降序查询Score表的所有记录。
select * from Score order by cno asc,degree desc
7.查询“95031”班的学生人数。
select count(*) fromstudentwhere class=‘95031’;
常见错误
1.Field ‘Ssex’ doesn’t have a default value
错误原因:
Ssex为非空字段,但是没有为其设置值
解决方法:
添加一个Ssex字段,并为其赋值