"Zero Basic" MySQL Super Introductory Tutorial

The old rules go to the town first

Introduction to MySQL

1. What is a database?

Database is a warehouse that organizes, stores and manages data according to the data structure. It was created more than 60 years ago. With the development of information technology and the market, especially after the 1990s, data management It is no longer just storing and managing data, but transforming into various data management methods required by users. There are many types of databases, from the simplest tables that store various data to large-scale database systems that can store massive amounts of data. They have been widely used in all aspects.

The mainstream databases are: sqlserver, mysql, Oracle, SQLite, Access, MS SQL Server, etc. This article mainly focuses on mysql

2. What is the purpose of database management?

  • a. Save data to file or memory
  • b. Receive specific commands, and then perform corresponding operations on the file

PS: If you have the above management systems, you don’t need to create files and folders yourself, but directly pass commands to the above software for file operations. They are collectively referred to as database management systems (DBMS, Database Management System)

MySQL installation

MySQL is an open source relational database management system (RDBMS). The MySQL database system uses the most commonly used database management language-Structured Query Language (SQL) for database management. In terms of WEB applications, MySQL is one of the best RDBMS (Relational Database Management System) application software.

The following conditions must be met to use mysql

  • a. Install MySQL server
  • b. Install MySQL client
  • c. [Client] Connect to [Server]
  • d. [Client] Send commands to the [Server MySQL] service to accept commands and perform corresponding operations (addition, deletion, modification, etc.)

1. Download address: http://dev.mysql.com/downloads/mysql/

2. Installation

Note: The above two links have a complete installation method. The master also refers to his installation. After the installation is complete, mysql.server start starts the mysql service

MySQL operation

One, connect to the database

mysql  -u user -p                   例:mysql -u root -p

Common errors are as follows:

ERROR 2002 (HY000): Can't connect to local MySQL server through socket'/tmp/mysql.sock' (2), it means that the MySQL server daemon (Unix) or service (Windows) is not running.

Exit the connection:

QUIT 或者 Ctrl+D

Second, view the database, create a database, use the database to view the database:

show databases;

Default database:

mysql - 用户权限相关数据test - 用于用户测试数据information_schema - MySQL本身架构相关数据

Create the database:

create database db1 DEFAULT CHARSET utf8 COLLATE utf8_general_ci; # utf8编码 create database db1 DEFAULT CHARACTER SET gbk COLLATE gbk_chinese_ci; # gbk编码

Use database:

use db1;

Display all tables in the currently used database:


Three, user management

Create user

create user '用户名'@'IP地址' identified by '密码';

delete users

drop user '用户名'@'IP地址';

Modify user

rename user '用户名'@'IP地址'; to '新用户名'@'IP地址';

change Password

set password for '用户名'@'IP地址' = Password('新密码');

Note: User permission related data is stored in the user table of the mysql database, so it can also be operated directly (not recommended)

Look so tired after so long, rest for 10 seconds and continue to look down

Four, authority management

MySQL has the following restrictions on permissions:

all privileges:除grant外的所有权限select:仅查权限select,insert:查和插入权限...usage:无访问权限alter:使用alter tablealter routine:使用alter procedure和drop procedurecreate:使用create tablecreate routine:使用create procedurecreate temporary tables:使用create temporary tablescreate user:使用create user、drop user、rename user和revoke  all privilegescreate view:使用create viewdelete:使用deletedrop:使用drop tableexecute:使用call和存储过程file:使用select into outfile 和 load data infilegrant option:使用grant 和 revokeindex:使用indexinsert:使用insertlock tables:使用lock tableprocess:使用show full processlistselect:使用selectshow databases:使用show databasesshow view:使用show viewupdate:使用updatereload:使用flushshutdown:使用mysqladmin shutdown(关闭MySQL)super:使用change master、kill、logs、purge、master和set global。还允许mysqladmin调试登陆replication client:服务器位置的访问replication slave:由复制从属使用

For the database and other internal permissions are as follows:

数据库名.*            数据库中的所有数据库名.表           指定数据库中的某张表数据库名.存储过程      指定数据库中的存储过程*.*                   所有数据库

The permissions for users and IP are as follows:

用户名@IP地址        用户只能在改IP下才能访问用户名@192.168.1.%   用户只能在改IP段下才能访问(通配符%表示任意)用户名@%             用户可以再任意IP下访问(默认IP地址为%)

1. View authority:

show grants for '用户'@'IP地址'

2. Authorization

grant  权限 on 数据库.表 to   '用户'@'IP地址'

3. Cancel authorization

revoke 权限 on 数据库.表 from '用户名'@'IP地址'

Examples of authorization are as follows:

grant all privileges on db1.tb1 TO '用户名'@'IP' grant select on db1.* TO '用户名'@'IP' grant select,insert on *.* TO '用户名'@'IP' revoke select on db1.tb1 from '用户名'@'IP' 

MySQL table operations

1. View the table

show tables; # 查看数据库全部表 select * from 表名; # 查看表所有内容

Two, create a table

create table 表名(    列名  类型  是否可以为空,    列名  类型  是否可以为空)ENGINE=InnoDB DEFAULT CHARSET=utf8

Come to an example for detailed explanation

CREATE TABLE `tab1` (  `nid` int(11) NOT NULL auto_increment,  `name` varchar(255) DEFAULT zhangyanlin,  `email` varchar(255),  PRIMARY KEY (`nid`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;


  • Default value, you can specify the default value when you create the column, and automatically add the default value if you do not actively set it when inserting data
  • Auto-increment, if you set an auto-increment column for a column, you don’t need to set this column when inserting data. It will auto-increment by default (there can only be one auto-increment column in the table). Note: 1. For an auto-increment column, it must be an index (including a primary key) ) 2. For auto-increment, the step size and starting value can be set
  • The primary key, a special unique index, does not allow null values. If the primary key uses a single column, its value must be unique, and if it is multiple columns, its combination must be unique.

Three, delete the table

drop table 表名

Four, clear the table content

delete from 表名truncate table 表名

Five, modify the table

添加列:    alter table 表名 add 列名 类型 删除列:    alter table 表名 drop column 列名 修改列:          alter table 表名 modify column 列名 类型;  -- 类型alter table 表名 change 原列名 新列名 类型; -- 列名,类型 添加主键:          alter table 表名 add primary key(列名); 删除主键:          alter table 表名 drop primary key;alter table 表名  modify  列名 int, drop primary key; 添加外键:  alter table 从表 add constraint 外键名称(形如:FK_从表_主表) foreign key 从表(外键字段) references 主表(主键字段); 删除外键:  alter table 表名 drop foreign key 外键名称 修改默认值: ALTER TABLE testalter_tbl ALTER i SET DEFAULT 1000; 删除默认值: ALTER TABLE testalter_tbl ALTER i DROP DEFAULT;

Do the above operations seem troublesome and time-consuming, don't panic! There is a special software that can provide these functions, and the operation is very simple. The name of this software is Navicat Premium. You can download it on the Internet and practice your hands. However, the following is about to talk about the contents of the table. It is recommended to write commands by yourself.

Six, basic data types

MySQL data types are roughly divided into: numeric value, time and string

bit[(M)]            二进制位(101001),m表示二进制位的长度(1-64),默认m=1 tinyint[(m)] [unsigned] [zerofill]             小整数,数据类型用于保存一些范围的整数数值范围:            有符号:                -128 ~ 127.            无符号:                0 ~ 255             特别的: MySQL中无布尔值,使用tinyint(1)构造。 int[(m)][unsigned][zerofill]             整数,数据类型用于保存一些范围的整数数值范围:                有符号:                    -2147483648 ~ 2147483647                无符号:                    0 ~ 4294967295             特别的:整数类型中的m仅用于显示,对存储范围无限制。例如: int(5),当插入数据2时,select 时数据显示为:00002 bigint[(m)][unsigned][zerofill]             大整数,数据类型用于保存一些范围的整数数值范围:                有符号:                    -9223372036854775808 ~ 9223372036854775807                无符号:                    0  ~  18446744073709551615 decimal[(m[,d])] [unsigned] [zerofill]             准确的小数值,m是数字总个数(负号不算),d是小数点后个数。 m最大值为65,d最大值为30。             特别的:对于精确数值计算时需要用此类型                   decaimal能够存储精确值的原因在于其内部按照字符串存储。 FLOAT[(M,D)] [UNSIGNED] [ZEROFILL]                        单精度浮点数(非准确小数值),m是数字总个数,d是小数点后个数。                无符号:                    -3.402823466E+38 to -1.175494351E-38,                    0                    1.175494351E-38 to 3.402823466E+38                有符号:                    0                    1.175494351E-38 to 3.402823466E+38             **** 数值越大,越不准确 **** DOUBLE[(M,D)] [UNSIGNED] [ZEROFILL]             双精度浮点数(非准确小数值),m是数字总个数,d是小数点后个数。                 无符号:                    -1.7976931348623157E+308 to -2.2250738585072014E-308                    0                    2.2250738585072014E-308 to 1.7976931348623157E+308                有符号:                    0                    2.2250738585072014E-308 to 1.7976931348623157E+308            **** 数值越大,越不准确 ****  char (m)             char数据类型用于表示固定长度的字符串,可以包含最多达255个字符。其中m代表字符串的长度。            PS: 即使数据小于m长度,也会占用m长度            varchar(m)             varchars数据类型用于变长的字符串,可以包含最多达255个字符。其中m代表该数据类型所允许保存的字符串的最大长度,只要长度小于该最大值的字符串都可以被保存在该数据类型中。             注:虽然varchar使用起来较为灵活,但是从整个系统的性能角度来说,char数据类型的处理速度更快,有时甚至可以超出varchar处理速度的50%。因此,用户在设计数据库时应当综合考虑各方面的因素,以求达到最佳的平衡 text             text数据类型用于保存变长的大字符串,可以组多到65535 (2**16 − 1)个字符。 mediumtext             A TEXT column with a maximum length of 16,777,215 (2**24 − 1) characters. longtext             A TEXT column with a maximum length of 4,294,967,295 or 4GB (2**32 − 1) characters. enum             枚举类型,            An ENUM column can have a maximum of 65,535 distinct elements. (The practical limit is less than 3000.)            示例:                CREATE TABLE shirts (                    name VARCHAR(40),                    size ENUM('x-small', 'small', 'medium', 'large', 'x-large')                );                INSERT INTO shirts (name, size) VALUES ('dress shirt','large'), ('t-shirt','medium'),('polo shirt','small'); set             集合类型            A SET column can have a maximum of 64 distinct members.            示例:                CREATE TABLE myset (col SET('a', 'b', 'c', 'd'));                INSERT INTO myset (col) VALUES ('a,d'), ('d,a'), ('a,d,a'), ('a,d,d'), ('d,a,d'); DATE                        YYYY-MM-DD(1000-01-01/9999-12-31) TIME             HH:MM:SS('-838:59:59'/'838:59:59') YEAR             YYYY(1901/2155) DATETIME             YYYY-MM-DD HH:MM:SS(1000-01-01 00:00:00/9999-12-31 23:59:59    Y) TIMESTAMP             YYYYMMDD HHMMSS(1970-01-01 00:00:00/2037 年某时) 

MySQL table content operation

The operation of table content is nothing more than adding, deleting, modifying and checking. Of course, the most used one is checking, and checking this piece is the most difficult to use. Of course, it is easy for the great gods, and it is still very difficult for me to be flexible. Used, let’s operate them one by one

One, increase

insert into 表 (列名,列名...) values (值,值,...)insert into 表 (列名,列名...) values (值,值,...),(值,值,值...)insert into 表 (列名,列名...) select (列名,列名...) from 表例:    insert into tab1(name,email) values('zhangyanlin','[email protected]')

Two, delete

delete from 表   # 删除表里全部数据delete from 表 where id=1 and name='zhangyanlin' # 删除ID =1 和name='zhangyanlin' 那一行数据

Three, change

update 表 set name = 'zhangyanlin' where id>1

Four, check

select * from 表select * from 表 where id > 1select nid,name,gender as gg from 表 where id > 1

There are too many conditions for checking this area. I will list them. As for the combination, it depends on everyone’s understanding.

a, conditional judgment where

select * from 表 where id > 1 and name != 'aylin' and num = 12;select * from 表 where id between 5 and 16;select * from 表 where id in (11,22,33)select * from 表 where id not in (11,22,33)select * from 表 where id in (select nid from 表)

b, wildcard like

select * from 表 where name like 'zhang%'  # zhang开头的所有(多个字符串)select * from 表 where name like 'zhang_'  # zhang开头的所有(一个字符)

c, limit limit

select * from 表 limit 5;            - 前5行select * from 表 limit 4,5;          - 从第4行开始的5行select * from 表 limit 5 offset 4    - 从第4行开始的5行

d, sort asc, desc

select * from 表 order by 列 asc              - 根据 “列” 从小到大排列select * from 表 order by 列 desc             - 根据 “列” 从大到小排列select * from 表 order by 列1 desc,列2 asc    - 根据 “列1” 从大到小排列,如果相同则按列2从小到大排序

e, group by

select num from 表 group by numselect num,nid from 表 group by num,nidselect num,nid from 表  where nid > 10 group by num,nid order nid descselect num,nid,count(*),sum(score),max(score),min(score) from 表 group by num,nidselect num from 表 group by num having max(id) > 10 特别的:group by 必须在where之后,order by之前 

Well, above we have completed the introduction to MySQL. After practice, some simple additions, deletions, corrections and checking tasks are no longer a problem. At this time, you should consider advanced

related suggestion:

"Java Boutique Design" based on java ssm springboot+mybatis winery internal management system (source code+sql+thesis)

"Java Boutique Complete Design" java ssm springboot second-hand goods mall project (complete source code + sql+ paper)

Java SSM (springboot) gourmet recipe sharing platform system (database + source code + papers)

Click to see more java boutique projects >>>

Okay, let's stop here today, friends like, favorite, comment, one-click three consecutive walks, see you in the next issue~~