- 1. 添加字段
- 2. 修改数据库字段为可为null
- 3. 修改数据库字段名
- 4. 添加主键索引
- 5. 添加唯一索引
- 6. 添加全文索引
- 7. 添加普通索引
- 8. 添加组合索引
- 9. 查询 if else --> CASE WHEN
- 10. 查看索引
- 11. 唯一约束
- 12. IFNULL 函数
- 13. DATE_SUB 函数
- 14.新建用户, 并支持远程连接
- 15 HAVING COUNT
困而学,学而知 好记性不如烂笔头
1. 添加字段
alter table 表名 add column 列名1 bigint(20) after 列名0; (新增的列1要放到列0之后)
2. 修改数据库字段为可为null
alter table 表名 modify column 列名 bigint(20) default null;
3. 修改数据库字段名
alter table 表名 CHANGE COLUMN `date` create_time date ;
4. 添加主键索引
ALTER TABLE `table_name` ADD PRIMARY KEY (`column`)
5. 添加唯一索引
ALTER TABLE `table_name` ADD UNIQUE (`column`)
6. 添加全文索引
ALTER TABLE `table_name` ADD FULLTEXT (`column`)
7. 添加普通索引
ALTER TABLE `table_name` ADD INDEX index_name (`column` )
8. 添加组合索引
ALTER TABLE `table_name` ADD INDEX index_name (`column1`, `column2`, `column3`)
9. 查询 if else --> CASE WHEN
SELECT buyer_nick, CASE types
WHEN 1 THEN
'恶意打假'
WHEN 2 THEN
'抽检'
ELSE
''
END as '黑名单类型'
from cloud_blacklist_mark;
10. 查看索引
show index from tablename
11. 唯一约束
11.1 添加唯一性约束
alter table tableName add unique(column_name)
11.2 查看唯一性约束
show keys from tableName;
#或
show index from tableName;
11.3 删除唯一性约束
alter table table_name drop index key_name;
12. IFNULL 函数
IFNULL() 函数用于判断第一个表达式是否为 NULL,如果为 NULL 则返回第二个参数的值,如果不为 NULL 则返回第一个参数的值。
IFNULL(expression, alt_value)
13. DATE_SUB 函数
函数从日期减去指定的时间间隔。
DATE_SUB(date,INTERVAL expr type)
14.新建用户, 并支持远程连接
14.1 创建user01,支持本地访问
create user user01@'localhost' identified by 'password';
14.2创建user02, 支持远程访问
create user user02@'%' identified by 'password';
14.3修改用户密码
set password for 'user01'@'localhost' = password('anotherpassword');
14.4授予user01管理test的全部权限
grant all privileges on test.* to user01;
14.5授予user02查看权限,并修改密码
grant select on *.* to 'user02'@'%' identified by 'anotherpassword';
14.6授予所有权限
GRANT ALL PRIVILEGES ON *.* TO user@"%" IDENTIFIED BY "lisi";
15 HAVING COUNT
需要和group by 联合使用
需求: 现在两个表,学生表t_student
、班级表t_class
和成绩表t_grade
。现需要统计有n那些班级达到100分的人数大于10人。(这个需求有点傻)
-- 班级表
create table t_class
(
id int auto_increment primary key,
name varchar(10) default '' not null,
teacher varchar(20) default '' not null
)
-- 班级表
create table t_grade
(
id int auto_increment primary key,
t_id int default 0 not null,
source decimal default 0 not null
)
-- 学生表
create table t_student
(
id int auto_increment primary key,
name varchar(20) default '' not null,
c_id int default 0 not null,
age int default 0 not null
)
select c.id, count(g.source)
from t_student s
inner join t_class c on s.c_id = c.id
inner join t_grade g on s.id = g.t_id
where g.source = 100
group by c.id
having count(g.source) > 10;