mysql常用操作
启动和连接mysql
-
查看mysql状态:
sudo service mysql status
-
启动/停止/重启服务:
sudo service mysql start/stop/restart
-
连接mysql
mysql -h主机地址 -u用户名 -p密码
-
关闭连接
ctrl + D
exit
数据库管理
-
查看已有数据库
show databases;
-
创建数据库
create database 库名 [character set utf8];
eg
create database stu character set utf8;
create database stu charset=utf8;
注意:库名的命名
- 数字、字母、下划线,但不能使用纯数字
- 库名区分字母大小写
- 不要使用特殊字符和mysql关键字
-
切换库
use 库名;
-
查看当前所在库
select database();
-
删除库
drop database 库名;
数据表管理
- 创建表
create table 表名(字段名 数据类型 约束,字段名 数据类型 约束,...字段名 数据类型 约束);
eg:
create table class_1 (
id int primary key auto_increment,
name varchar(32) not null,
age tinyint unsigned not null,
sex enum('w','m'),
score float default 0.0);
-
查看数据表
show tables;
-
查看表结构
desc 【表名】;
-
查看数据表创建信息
show create table 【表名】;
-
删除表
drop table 【表名】;
-
修改表名
alter table 【表名】rename to 【新表名】
表字段操作
语法:alter table 【表名】 执行动作;
* 添加字段(add)
alter table 【表名】 add 【字段名】 数据类型;
alter table 【表名】 add 【字段名】 数据类型 first;
alter table 【表名】 add 【字段名】 数据类型 after 【字段名】;
* 删除字段(drop)
alter table 【表名】 drop 【字段名】;
* 修改数据类型(modify)
alter table 【表名】 modify 【字段名】 新数据类型;
* 修改字段名(change)
alter table 【表名 】change 【旧字段名】 【新字段名】 新数据类型;
* 表重命名(rename)
alter table 【表名】 rename 【新表名】;
表数据操作
- 插入数据(insert)
insert into 【表名】 values(值1),(值2),...;
insert into 【表名】(字段1,...) values(值1),...;
- 修改数据(update)
update 【表名】 set 字段1=值1,字段2=值2,... where 【条件】;
- 删除表记录(delete)
delete from 【表名】 where 【条件】;
- 查找表记录(select)
select * from 【表名】 [where 条件];
select 字段1,字段2 from 【表名】 [where 条件];
高级查询语句
- 模糊查询和正则查询
- 模糊查询
LIKE用于在where子句中进行模糊查询,SQL LIKE 子句中使用百分号%
来表示任意0个或多个字符,下划线_
表示任意一个字符。
mysql> select * from class_1 where name like 'A%';
- 正则查询
mysql中对正则表达式的支持有限,只支持部分正则元字符:
select * from class_1 where name regexp '^B.+';
- as
- as 用法
在sql语句中as用于给字段或者表重命名
select name as 姓名,age as 年龄 from class_1;
select * from class_1 as c where c.age > 17;
- 排序(order by)
ORDER BY 子句来设定你想按哪个字段哪种方式来进行排序,再返回搜索结果。
默认情况ASC表示升序,DESC表示降序
使用 ORDER BY 子句将查询数据排序后再返回数据:
select * from class_1 order by score desc,age;
- 限制(limit)
LIMIT 子句用于限制由 SELECT 语句返回的数据数量 或者 UPDATE,DELETE语句的操作数量
SELECT column1, column2, columnN
FROM table_name
WHERE field
LIMIT [num]
- 联合查询(union)
UNION 操作符用于连接两个以上的 SELECT 语句的结果组合到一个结果集合中。
默认UNION后为【DISTINCT】表示删除结果集中重复的数据。如果使用【ALL】则返回所有结果集,包含重复数据。
select * from class_1 where sex='m' UNION ALL select * from class_1 where age > 9;
- 子查询
select name from (select * from class_1 where sex='m') as s where s.score > 90;
干净的圈子 规律的生活 中意的人。