2.4. 数据库的操作:(★★)
1、 show databases;
2、show create database 库名;
3、create database 数据库名;
4、create database 数据库名 character set 编码表名;
5、alter database 数据库名称 character set 字符集 [collate 排序规则];
6、select database();
7、use 数据库名;
2.5. 数据表结构的添查删改(★★★)
1、 create table 表名(
列名 类型(长度),
列名 类型(长度)...
);
2、desc 表名;
3、create table emp2(
id int primary key auto_increment,
username varchar(50) unique not null,
password varchar(50) not null,
sex char(10),
birthday date
);
4、alter table 表名 增/删/改 列名 类型(长度) 约束;
5、alter table 表名 modify 列名 类型(长度) 约束;
6、alter table 表名 change 旧列名 新列名 类型(长度) 约束;
7、alter table 表名 drop 列名;
8、rename table 旧表名 to 新表名;
9、alter table 表名 character set 编码集;
10、drop table 表名;
11、show tables;
12、desc 表名;
13、show create table 表名;
2.6. 简单数据表内容的增删改(★★★★)
CRUD。
create read update delete
1、insert into 表名 (列名,列名,列名......) values (值,值,值......);
(省略和注意事项)
2、update 表名 set 列名=值,列名=值.... [ where条件语句 ];
(注意事项)
3、delete from 表名 [where条件语句]
4、TRUNCATE TABLE 表名
5、TRUNCATE 表名
3.1. 数据表记录的查询 (★★★★★)
1、select * from 表名;
2、select 列名,列名... from 表名;
3、select 列名,列名..... from 表名 where 条件;
(运算符:相等= 不等 <> !=
and 逻辑与, or 逻辑或, not 逻辑非
age >=24 and age<=50 等价于 age between 24 and 50
in(70,80,90)
like '模糊查询pattern' 进行模糊查询 ,表达式有两个占位符 % 任意字符串, _ 任意单个字符
is null; is not null;
)
3.1.5. 语法四 :过滤重复数据:
1、select distinct 列名 from 表名 [where 条件];
2、select * from 表名 order by 列名 asc|desc ;
3.1.7. 别名:可以对查询出来的列名 起别名。
1、select 列名 as 别名,列名 as 别名,列名 as 别名.... from 表名 where 条件;
3.2. SQL中的聚合函数
count 统计个数(行数)
sum函数:求和
avg函数:求平均值
max、min 求最大值和最小值
1、select count(*)|count(列名) from 表名
(注意:有null 不会被统计在其中。)
2、select sum(列名) from 表名;
(注意:1、如果使用sum 多列进行求和的时候,如果某一列中的有null,这一列所在的行中的其他数据不会被加到总和。
2、可以使用mysql 数据库提供的函数 ifnull(列名,值)
3、在数据库中定义double类型数据,是一个近似值,需要确定准确的位数,这时可以把这一列设计成numeric类型。numeric(数据的总列数,小数位数)
numeric double float
)
3、truncate(列名, 小数的位数)
1、select avg(列名) from 表名;
2、Max/min函数返回满足where条件的一列的最大/最小值
3、select … from … group by 列名,列名
综上:select 6 from 1 where 2 group by 3 having 4 order by 5;
面试题1
1、delete删除表中的数据时没有加where 条件,会删除表中的所有数据,它与truncate 有什么区别?
1.DELETE
・DML语言
・可以回退(可以将数据找回来)
・可以有条件的删除
DELETE FROM 表名 WHERE 条件
2.TRUNCATE TABLE
・DDL语言
・无法回退(不可以将数据找回来)
・默认所有的表内容都删除
・删除速度比delete快。
TABLE 表名
TRUNCATE 表名
2、delete from person; 和 drop table person; 有什么区别:
delete from person; 把person表中的所有数据全部删除,但是person的表还存在。
drop table person; 把person数据表从数据库中删除。
3、select age score from student;
select age, score from student;
什么区别?
第一个是把查询出来的学生年龄 起别名为score。第二个是查询 当前student表中中的age 和score两列数据。