创建表,语法:
create table 表名(
#省略代码
);
删除表,语法:
drop table 表名;
查看表,语法:
select * from 表名;
desc 表名; 查询表的结构
修改表名,语法:
alter table 旧表名 rename 新表名;
添加字段,语法:
alter table 表名 add 字段名 数据类型 [属性];
修改字段名,语法:
alter table 表名 change 旧字段名 新字段名 数据类型[属性];
删除字段,语法:
alter table 表名 drop 字段名;
添加主键,语法:
ALTER
TABLE 表名 ADD CONSTRAINT 主键名
PRIMARY KEY 表名(主键字段);
建立外键关联,语法:
ALTER TABLE 表名 ADD CONSTRAINT 外键名
FOREIGN KEY (外键字段)
REFERENCES 关联表名(关联字段);
下面都是对表里的数据做一些增删改查,对表本身没操作
给表插入数据,语法:
insert [into] 表名 values (需要插入的数据)#插入的数据必须按建立表时候的字段和字段属性要求来依次插入并以逗号隔开)
给表插入多条数据:
insert [into] 表名 values (第1条数据),(第2条数据),(第3条数据) #数据之间逗号隔开
#中括号中的into可写可不写
为特定列插入值,语法:
insert [into] 表名 (字段1,字段2,字段3)values (字段1的值,字段2的值,字段3的值)
特点:指定顺序,列值对应
修改全部数据,语法:
update 表名 set 字段名=修改后的值
示例:你想把一个表名为student的字段名为sex的值全部改为“男”
update student set sex='男';
修改特定数据,意思是把符合条件的数据进行修改,不符合条件的不管,语法:
update 表名 set字段名=修改后的值 where 条件表达式
#where 后面是条件,满足条件就修改前面的数据,不满足条件就不去修改
示例:把字段qq为12345的sex改为'女'
update 表名 set sex='女' where qq='12345'
使用delete命令删除数据,语法:
delete [from] 表名 where 条件语句;# from可不写
示例:删除student表中字段sex值为'女'的所有信息
delete from student where sex='女';
使用truncate table 删除数据,语法:
truncate table 表名; #truncate 不可以加条件where
示例:删除student表中所有的数据
truncate table student;
下面都是一些查询数据操作
查询基础,语法:
select 表1的字段,表2的字段 ,表N的字段
from 表1,表2,表N
[where 条件语句]
[group by……] #用来给查询的结果分组
[having……] #用统计结果作为条件
[order by……] #对查询的结果进行排序
简单查询:
查询全部数据:
select * from 表名;
查询某字段的所有数据:
select 某字段 from 表名;
查询的时候别名的使用:
select 字段名 as 别名 from 表名;
disyinct关键字查询,作用:消除结果集中的重复行。语法:
select distinct 字段名 from 表名;
limit关键字查询, 作用:指定结果集中数据的显示范围。语法:
示例:显示student表中第2条到第6条的数据
select * from student limit 1,5
普通条件查询:
示例:查询student表中字段name中值为'韩道红'的数据:
select * from student where name='韩道红'
条件查询会用到一些比较运算符:
等于 =
不等于<>
大于>
小于<
大于等于>=
小于等于<=
逻辑运算符:
并且:and
或者:or
非: not
示例:查询student表中字段name为'韩道红'且字段sex为'男'的数据
select * from student where name='韩道红' and sex='男'
模糊查询:示例:查询scores表中字段score的值大于等于2000并且小于等于3000的数据
select *from scores where score between 2000 and 3000;
示例:查询不在scores表中字段score的值大于等于2000并且小于等于3000的数据# 在between之前加个not就好
select *from scores where score not between 2000 and 3000;
通配符:
'_' : 代表一个字符
% :代表任意长度,任意字符
[] :指定范围内
[^]: 不在括号中的字符
示例: 在student 表中查询字段name的值为姓'孙……'的数据
select * from student where name like '孙%';
示例: 在student 表中查询字段name的值不为姓'孙……'所有数据
select * from student where name not like '孙%';#在like之前加一个not 就好
查询空值的运算符:
示例:查询student表中字段name值为null的数据
select * from student where name is null
示例:查询student表中字段name值不为null所有数据
select * from student where name is not null
排序:对指定字段排序:
1.排序依据
按照什么条件排序,是身高,还是体重,这就是依据
2.排序方式:
1.升序排序
2.降序排序
示例:查询scores表中sNo为1的数据,并按照score升序排序
select * from scores where sNo=1 order by score asc
示例:查询scores表中sNo为1的数据,并按照score升序排序
select * from scores where sNo=1 order by score desc
对多字段排序:
示例:对sno进行升序排序,对score 进行降序排序
select * from scores order by sNo asc , score desc; #排序的优先级 前面的sNo优先级更高