Mysql数据库基础笔记

一、前言

  • mysql和linux php,apache配合紧密,LAMP架构
  • mysql开源免费
  • 默认端口3306
  • set name gbk

二、安装启动服务

mysqld -install
net start mysql
mysql -uroot -proot

三、修改用户密码

mysql> set password for root@localhost=password('root');			//加密码
mysql> select user,password from mysql.user;						//查看密码
mysql> use mysql;
mysql> update user set password=password('123') where user='root';	//改密码
mysql> flush privileges;											//刷新权限

忘记root密码

  1. 关闭正在运行的MySQL服务
  2. 管理员运行DOS窗口,转到mysql\bin目录
  3. mysqld --skip-grant-tables //启动MySQL服务的时候跳过权限表认证
  4. 再开一个DOS窗口(因为刚才那个DOS窗口已经不能动了),输入mysql回车
  5. 修改密码
  6. 重启服务

四、基本语句

1.库操作

mysql> show databases;						//查库
mysql> use mysql;							//选库
mysql> create database db1 charset utf8;	//创建库
mysql> drop database db1;					//删除数据库
											//mysql中数据库不能改名,表/列可以改名

2.表操作

mysql> show tables;							//查表
+---------------+
| Tables_in_db1 |
+---------------+
| class         |
| student       |
+---------------+
mysql> create table student(				//创建表
    -> Snum int,
    -> Sname varchar(10),
    -> Ssex char(2)
    -> )engine myisam charset utf8;
mysql> drop table student;					//删除表
mysql> rename table student to stu;			//重命表名
mysql> insert into stu values				//插入数据
    -> (1,'张三'),
    -> (2,'lisi'),
    -> (3,'王五');
mysql> select * from stu;					//查数据
mysql> truncate stu;						//清空表数据
mysql> insert into student values
    -> \c									//退出本语句
mysql> create table class(					//创建表
    -> id int primary key auto_increment,
    -> sname varchar(10) not null default '',
    -> sex char(1) not null default '',
    -> company varchar(20) default 'null',
    -> salary decimal(6,2) default 0.00,
    -> other varchar(20) default '无'
    -> )engine myisam charset utf8;
mysql> desc class;							//查看表结构
+---------+--------------+------+-----+---------+----------------+
| Field   | Type         | Null | Key | Default | Extra          |
+---------+--------------+------+-----+---------+----------------+
| id      | int(11)      | NO   | PRI | NULL    | auto_increment |
| sname   | varchar(10)  | NO   |     |         |                |
| sex     | char(1)      | NO   |     |         |                |
| company | varchar(20)  | YES  |     | null    |                |
| salary  | decimal(6,2) | YES  |     | 0.00    |                |
| other   | varchar(20)  | YES  |     | 无      |                |
+---------+--------------+------+-----+---------+----------------+
mysql> alter table class add score tinyint unsigned not null default 0;	//增加一个score列
mysql> alter table student add money float(7,2) default 0;

五、数据操作

1、增——Insert

mysql> insert into class
    -> (id,sname,sex,company,salary,other) values (1,'张三','女','','10000.00','工作地址在广州');
mysql> insert into class
    -> (sname,sex,salary) values ('李四','女','9000');
mysql> insert into class (sname) values ('王五');
mysql> insert into class (sname) values ('王五'),('赵六'),('顾七'); 
mysql> insert into class values
    -> (7,'吴八','男','百度',8734.32,'深圳任职');
mysql> select * from class;
+----+-------+-----+---------+---------+----------------+
| id | sname | sex | company | salary  | other          |
+----+-------+-----+---------+---------+----------------+
|  1 | 张三  | 女  |         | 9999.99 | 工作地址在广州 |
|  2 | 李四  | 女  | null    | 9000.00 | 无             |
|  3 | 王五  |     | null    |    0.00 | 无             |
|  4 | 王五  |     | null    |    0.00 | 无             |
|  5 | 赵六  |     | null    |    0.00 | 无             |
|  6 | 顾七  |     | null    |    0.00 | 无             |
|  7 | 吴八  | 男  | 百度    | 8734.32 | 深圳任职       |
+----+-------+-----+---------+---------+----------------+
mysql> insert into db1.goods select goods_id,cat_id,goods_name from gyshop.goods;															//从其他库导入插入数据,要求导入所有列

2、改——Update

  • update 表名 set 列1=’ ‘,列2=’ ’ where expr;
mysql> update class set sex='男',company='皇家亲戚' where sname='王五';
mysql> update class set salary = 5000 where salary =0.00;
mysql> update class set other = '目前离职状态' where salary <=9000 and sex = '';
mysql> select * from class;
+----+-------+-----+----------+---------+----------------+
| id | sname | sex | company  | salary  | other          |
+----+-------+-----+----------+---------+----------------+
|  1 | 张三  | 女  | 千度     | 9999.99 | 工作地址在广州 |
|  2 | 李四  | 女  | 千度     | 9000.00 | 无             |
|  3 | 王五  | 男  | 皇家亲戚 | 5000.00 | 无             |
|  4 | 王五  | 男  | 皇家亲戚 | 5000.00 | 无             |
|  5 | 赵六  |     | 千度     | 5000.00 | 目前离职状态   |
|  6 | 顾七  |     | 千度     | 5000.00 | 目前离职状态   |
|  7 | 吴八  | 男  | 百度     | 8734.32 | 深圳任职       |
+----+-------+-----+----------+---------+----------------+

3、删——Delete

  • delete from 表名 where expr;
mysql> delete from class where sname ='王五' or company='百度';
mysql> select * from class;
+----+-------+-----+---------+---------+----------------+
| id | sname | sex | company | salary  | other          |
+----+-------+-----+---------+---------+----------------+
|  1 | 张三  | 女  | 千度    | 9999.99 | 工作地址在广州 |
|  2 | 李四  | 女  | 千度    | 9000.00 | 无             |
|  5 | 赵六  |     | 千度    | 5000.00 | 目前离职状态   |
|  6 | 顾七  |     | 千度    | 5000.00 | 目前离职状态   |
+----+-------+-----+---------+---------+----------------+
mysql> delete from class;									//直接删除所有表数据
mysql> select * from class;
Empty set (0.00 sec)
mysql> truncate stu;										//清空表数据

4、查——Select

  • select 列1,列2,列n from 表名 where expr;
mysql> select * from class;								//查表所有数据
+----+-------+-----+---------+--------+-------+
| id | sname | sex | company | salary | other |
+----+-------+-----+---------+--------+-------+
|  8 | 张三  | 男  | null    |   0.00 | 无    |
|  9 | 李四  | 女  | null    |   0.00 | 无    |
| 10 | 王五  | 女  | null    |   0.00 | 无    |
+----+-------+-----+---------+--------+-------+
mysql> select sname from class where sex='女';			//查询指定列数据
+-------+
| sname |
+-------+
| 李四  |
| 王五  |
+-------+

1. where条件查询

where是针对原表的一个表达式布尔判断

mysql> select goods_id,goods_name from goods where goods_id = 2;
mysql> select goods_id,goods_name from goods where goods_id != 2;
mysql> select goods_id,goods_name from goods where goods_id <> 2;
mysql> select goods_id,goods_name from goods where shop_price > 2000;
mysql> select goods_id,goods_name from goods where shop_price >= 4;
mysql> select goods_id,goods_name from goods where goods_id in (1,4);
mysql> select goods_id,goods_name from goods where goods_id between 2 and 4;
mysql> select goods_id,goods_name from goods where goods_name like '平板%';
mysql> select goods_id,goods_name from goods where goods_name like '%平板%';
mysql> select goods_id,goods_name from goods where goods_name like '__平板';
mysql> select goods_id,goods_name from goods where goods_name like '手机K_';
mysql> select goods_id,goods_name from goods where goods_id != 2 and goods_id !=3;
mysql> select goods_id,goods_name from goods where goods_id not in (2,3);
mysql> select goods_id,goods_name from goods where goods_name not like '平板%';
mysql> select goods_id,goods_name from goods where goods_id > 1 and goods_id < 3 or goods_id > 4 and goods_id < 7;
mysql> select goods_id,goods_name from goods where shop_price >= 4 and goods_id > 4 and goods_id < 7;
mysql> select goods_id,goods_name from goods where shop_price = 0 and (goods_id < 4 or goods_id > 7 and goods_id <= 9) and goods_name like '%平板%';
mysql> select goods_name,market_price-shop_price from goods where 1;
mysql> select goods_name,(market_price-shop_price) as discount from goods where 1;
mysql> select goods_name,(market_price-shop_price) as discount from goods where (market_price-shop_price) > 1000;

2.group by分组查询

  • 五个聚合函数:sum,avg,max,min,count,group
mysql> select max(market_price) from goods;
mysql> select min(market_price) as MIN from goods;
mysql> select sum(goods_number) from goods;
mysql> select sum(goods_number) from goods where cat_id=3;
mysql> select avg(shop_price) from goods;
mysql> select count(*) from goods;
mysql> select cat_id,count(*),sum(market_price) from goods group by cat_id;
  • 严格的讲,以group by a,b,c为列,则select的列只能在a,b,c里选择,语义上才没有矛盾;

3.having 筛选

mysql> select goods_name,(market_price-shop_price) as discount from goods where (market_price-shop_price)>=500;
+----------------+----------+
| goods_name     | discount |
+----------------+----------+
| 手机           |  1100.00 |
| 平板屏幕总成   |   500.00 |
| 平板屏幕单机版 |   500.00 |
+----------------+----------+
mysql> select goods_name,(market_price-shop_price) as discount from goods having discount >= 500;
+----------------+----------+
| goods_name     | discount |
+----------------+----------+
| 手机           |  1100.00 |
| 平板屏幕总成   |   500.00 |
| 平板屏幕单机版 |   500.00 |
+----------------+----------+
mysql> select cat_id,sum(market_price) as discount from goods group by cat_id having discount >5000;
+--------+----------+
| cat_id | discount |
+--------+----------+
|      2 |  6000.00 |
|      3 |  7997.00 |
+--------+----------+ 
mysql> select name,avg(score),sum(score<60) as gk from result group by name having gk>=2;

4.order by 排序


5、limit 限制结果条数


六、表操作

1、增——Create

mysql> create table db1.member(										//建表
    -> id int unsigned auto_increment primary key,
    -> username char(20) not null default '',
    -> gender char(1) not null default '',
    -> weight tinyint unsigned not null default 0,
    -> birth date not null default 0,
    -> salary decimal(8,2) not null default 0,
    -> lastlogin timestamp not null default 0
    -> )engine myisam charset utf8;
mysql> show create table member;								//查看建表语句
+--------+------------------------------------------------------------------------------+
| Table  | Create Table                                                                 |
+--------+------------------------------------------------------------------------------+
| member | CREATE TABLE `member` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `username` char(20) NOT NULL DEFAULT '',
  `gender` char(1) NOT NULL DEFAULT '',
  `weight` tinyint(3) unsigned NOT NULL DEFAULT '0',
  `birth` date NOT NULL DEFAULT '0000-00-00',
  `salary` decimal(8,2) NOT NULL DEFAULT '0.00',
  `lastlogin` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 |
+--------+------------------------------------------------------------------------------+

2、改——Alter

mysql> alter table student add age tinyint not null default 0;	//默认加的列在表最后
mysql> alter table test add gender char(1) not null default 0 after star;	
																//把新列加在某列后
mysql> alter table test add id int unsigned not null auto_increment primary key first;																	//把新列加载最前面
mysql> alter table test drop gender;							//删除列
mysql> alter table test modify gender char(4) not null default '';																						//修改列类型
mysql> alter table test change gender sex char(2);				//修改列名和列类型

3、删——Drop

mysql> drop table student;	

4、查——Show

mysql> show tables;			//查表名
mysql> desc student;		//查表结构

九、其他

1.保存操作记录

mysql> tee C:\Users\LQN\Desktop\Temp\0525.sql
Logging to file 'C:\Users\LQN\Desktop\Temp\0525.sql'
mysql> #把敲的sql及结果都输出到一个sql文件里
mysql> #便于溯源

2.数据类型

整型:
类型 大小 参数 范围
tinyint 1 unsigned/zerofill 0-255/-128-127
smallint 2 unsigned/zerofill 0-65535/-32768-32767
mediumint 3 unsigned/zerofill
int 4 unsigned/zerofill
bigint 8 unsigned/zerofill
浮点型:
类型 大小 描述
float(M,D) 4/8 M叫“精度”,代表“总位数”
decimal(M,D) D是“标度”,代表“小数位”
mysql> alter table student add money float(7,2) default 0;
字符串型:
类型 描述 长度
char 定长类型 尾部空格补够长度 0-255
varchar 变长类型 有1-2个字节来标志该列的内容长度 0-65535
text 文本类型 搜索速度慢
blob 二进制类型 存储图像和音频等二进制信息
日期/时间类型:
类型 说明 标准格式 范围
date 日期 YYYY-MM-DD 1000-01-01到9999-12-31
time 时间 HH:MM:SS
datetime 日期时间 YYYY-MM-DD HH:MM:SS
year 年份类型 YYYY 1901-2155
timestamp 时间戳 默认插入数据的 当前时间

十、SQL优化

1)基本写法优化

  1. 少使用select * ,尽量使用具体字段;
  2. 对于条件来说等号之类两边的字段类型要一致,字符串不加单引号索引会失效;
  3. 尽量少使用Order by 排序,对于需要多个字段进行排序的可以使用组合索引;
  4. 对于groud by语句要先过滤后分组;
  5. 在查询时减少使用null,对字段有多个null的可以加默认值;
  6. 少使用like,对于需要使用的,如需要使用尽量用like abc%这种,不要把%放字段前面;
  7. 在where后面少使用函数或者算数运算;
  8. 去除的distinct过滤字段要少,避免distinct *;
  9. 不要超过5个以上的表连接。

2)建立使用合适索引

  1. 对于高频筛选字段可以适当的建立索引;
  2. 一个表的索引最好不要超过5个,多了会影响插入修改;
  3. 不要对值是有限重复的字段建立索引,如性别等;
  4. 使用组合索引一定要遵守最左原则。

3)替代优化

  1. 不要使用not in 和<>,这个会破会索引,not in 可以用not exists来代替,<>可以分成两个条件>或者|<等;
  2. 使用连接(join)来代替子查询;

十一、函数

1、Floor

floor(X):取整函数

mysql> select floor(1.23)
+-------------+
| floor(1.23) |
+-------------+
|           1 |
+-------------+
mysql> update test set num = floor(num/10)*10 where num >= 20 and num <= 39;
														//把二十几和三十几的都改为20和30

2、Substring

截取字符串

substring(str,pos,len)、substring(str,pos)、substring(str from pos)、substring(str from pos for len)

min(str,pos,len)等同

mysql> select substring('今天天气真好!',3);
+-------------------------------+
| substring('今天天气真好!',3) |
+-------------------------------+
| 天气真好!                    |
+-------------------------------+

mysql> select substring('今天天气真好!',3,2);
+---------------------------------+
| substring('今天天气真好!',3,2) |
+---------------------------------+
| 天气                            |
+---------------------------------+

mysql> select substring('今天天气真好!' from 3);
+------------------------------------+
| substring('今天天气真好!' from 3) |
+------------------------------------+
| 天气真好!                         |
+------------------------------------+

mysql> select substring('今天天气真好!' from 3 for 2) as '截取字符串';
+------------+
| 截取字符串 |
+------------+
| 天气       |
+------------+

3、Concat

mysql> select goods_name,concat('荣耀',substring(goods_name from 3)) from goods where goods_name like '__平板';
+------------+---------------------------------------------+
| goods_name | concat('荣耀',substring(goods_name from 3)) |
+------------+---------------------------------------------+
| 苹果平板   | 荣耀平板                                    |
| 华为平板   | 荣耀平板                                    |
+------------+---------------------------------------------+
mysql> update goods set goods_name=concat('荣耀',substring(goods_name from 3)) where goods_name like '__平板';

4、Count

求总行数

count(*)和count(1)取的是绝对的行数,哪怕某一行所有字段全为NULL也计算在内

count(列名)取的是该列不为null的所有行的行数

mysql> select count(*) from goods;
mysql> select count(goods_sn) from goods;

你可能感兴趣的:(MYSQL,数据库,mysql)