Home > Database > Mysql Tutorial > Analysis of basic operation examples of MySQL database

Analysis of basic operation examples of MySQL database

WBOY
Release: 2023-05-26 23:27:54
forward
1737 people have browsed it

1. Introduction to MySQL

1. Database management software classification

is mainly divided into relational and non-relational.

It can be simply understood that relational databases need to have a table structure, while non-relational databases are key-value stored and do not have a table structure.

Relational type: such as sqllite, db2, oracle, access, sql server, MySQL. Note: sql statements are universal.

Non-relational: mongodb, redis, memcache

2, MySQL

MySQL is a relational database management system developed by the Swedish MySQL AB company and currently belongs to Oracle product.

MySQL is one of the most popular relational database management systems. In terms of WEB applications, MySQL is the best RDBMS (relational database management system) application software.

SQL language is the most commonly used standardized language and is used to access the MySQL database. MySQL software adopts a dual licensing policy and is divided into community version and commercial version. Due to its small size, fast speed, low total cost of ownership, and especially the characteristics of open source, MySQL is generally chosen as the website database for the development of small and medium-sized websites.

MySQL provides us with open source installation packages for installation on various operating systems, including mac, linux, and windows.

2. Storage engine (also called table type)

Data in MySQL is stored in files (or memory) using various technologies. Different technologies use their own unique storage mechanisms, indexing techniques, and locking levels, thus providing a variety of functionality and capabilities. MySQL refers to these different technologies and related functions as storage engines, which can also be called table types.

MySQL is configured with many different storage engines by default, which can be preset or enabled in the MySQL server.

1. Common storage engines and applicable scenarios

  • InnoDB: Used for transaction processing applications, supporting foreign keys and row-level locks. If the application has relatively high requirements for the integrity of things and requires data consistency under concurrent conditions, and data operations include many update and delete operations in addition to insertion and query, then the InnoDB storage engine is more suitable.
    In addition to effectively reducing locks caused by deletions and updates, InnoDB can also ensure complete submission and rollback of transactions. It is a suitable choice for systems such as billing systems or financial systems that have high requirements for data accuracy. .

  • MyISAM: If the application is mainly based on read operations and insert operations, there are only a few update and delete operations, and the integrity and concurrency of the transaction are If the requirements are not high, then you can choose this storage engine.

  • Memory: Saves all data in memory, providing extremely fast access in environments where records and other similar data need to be quickly located.
    The flaw of Memory is that there is a limit on the size of the table. Although the data can be recovered normally if the database terminates abnormally, once the database is closed, the data stored in the memory will be lost.

The storage engines supported by mysql include InnoDB, MyISAM, MEMORY, CSV, BLACKHOLE, NDB, FEDERATED, MRG_MYISAM, ARCHIVE, PERFORMANCE_SCHEMA.
Among them, NDB and InnoDB provide transaction-safe tables, and other storage engines are non-transaction-safe tables.

2. The use of storage engine in mysql

# 查看当前的默认存储引擎:
mysql> show variables like "default_storage_engine";

# 查询当前数据库支持的存储引擎
mysql> show engines \G;
Copy after login
1. Specify the storage engine when creating the table
mysql> create table ai(id bigint(12),name varchar(200)) ENGINE=MyISAM; 
mysql> create table country(id int(4),cname varchar(50)) ENGINE=InnoDB;

# 也可以使用alter table语句,修改一个已经存在的表的存储引擎。
mysql> alter table ai engine = innodb;
Copy after login
2. Specify the storage engine in the configuration file
# my.ini文件
[mysqld]
default-storage-engine=INNODB
Copy after login

3. MySQL table operations

1. View table structure

There are two ways to view table structure:

  • desc[tablename] and describe [tablename]: These two methods have the same effect and can view the current table structure.

  • show create table [tablename]: In addition to seeing the table definition, you can also see information such as engine (storage engine) and charset (character set). Use the \G option to arrange records vertically, making longer records easier to display. )

Example:

mysql> desc staff_info;
+-------+-----------------------+------+-----+---------+-------+
| Field | Type                  | Null | Key | Default | Extra |
+-------+-----------------------+------+-----+---------+-------+
| id    | int(11)               | YES  |     | NULL    |       |
| name  | varchar(50)           | YES  |     | NULL    |       |
| age   | int(3)                | YES  |     | NULL    |       |
| sex   | enum('male','female') | YES  |     | NULL    |       |
| phone | bigint(11)            | YES  |     | NULL    |       |
| job   | varchar(11)           | YES  |     | NULL    |       |
+-------+-----------------------+------+-----+---------+-------+
rows in set (0.00 sec)

mysql> show create table staff_info\G;
*************************** 1. row ***************************
       Table: staff_info
Create Table: CREATE TABLE `staff_info` (
  `id` int(11) DEFAULT NULL,
  `name` varchar(50) DEFAULT NULL,
  `age` int(3) DEFAULT NULL,
  `sex` enum('male','female') DEFAULT NULL,
  `phone` bigint(11) DEFAULT NULL,
  `job` varchar(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8
row in set (0.01 sec)

ERROR: 
No query specified
Copy after login

2. Automatic growth column

The constrained field is automatically grown, and the constrained field must be constrained by the key primary key at the same time

--不指定id,则自动增长
create table student(id int primary key auto_increment,name varchar(20),sex enum('male','female') default 'male');

mysql> desc student;
+-------+-----------------------+------+-----+---------+----------------+
| Field | Type                  | Null | Key | Default | Extra          |
+-------+-----------------------+------+-----+---------+----------------+
| id    | int(11)               | NO   | PRI | NULL    | 
auto_increment  |
| name  | varchar(20)           | YES  |     | NULL    |                |
| sex   | enum('male','female') | YES  |     | male    |                |
+-------+-----------------------+------+-----+---------+----------------+
mysql> insert into student(name) values ('nick'),('tank') ;

mysql> select * from student;
+----+------+------+
| id | name | sex  |
+----+------+------+
|  1 | nick | male |
|  2 | tank | male |
+----+------+------+


--也可以指定id
mysql> insert into student values(4,'asb','female');
Query OK, 1 row affected (0.00 sec)

mysql> insert into student values(7,'wsb','female');
Query OK, 1 row affected (0.00 sec)

mysql> select * from student;
+----+------+--------+
| id | name | sex    |
+----+------+--------+
|  1 | nick | male   |
|  2 | tank | male   |
|  4 | asb  | female |
|  7 | wsb  | female |
+----+------+--------+


--对于自增的字段,在用delete删除后,再插入值,该字段仍按照删除前的位置继续增长
mysql> delete from student;
Query OK, 4 rows affected (0.00 sec)

mysql> select * from student;
Empty set (0.00 sec)

mysql> insert into student(name) values('ysb');
mysql> select * from student;
+----+------+------+
| id | name | sex  |
+----+------+------+
|  8 | ysb  | male |
+----+------+------+

--应该用truncate清空表,比起delete一条一条地删除记录,truncate是直接清空表,在删除大表时用它
mysql> truncate student;
Query OK, 0 rows affected (0.01 sec)

mysql> insert into student(name) values('nick');
Query OK, 1 row affected (0.01 sec)

mysql> select * from student;
+----+------+------+
| id | name | sex  |
+----+------+------+
|  1 | nick | male |
+----+------+------+
row in set (0.00 sec)

--在创建完表后,修改自增字段的起始值
mysql> create table student(id int primary key auto_increment, name varchar(20),sex enum('male','female') default 'male');
mysql> alter table student auto_increment=3 ;
mysql> show create table student;
.......
ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8

--也可以创建表时指定auto_increment的初始值,注意初始值的设置为表选项,应该放到括号外
mysql> create table student(id int primary key auto_increment, name varchar(20),sex enum('male','female') default 'male' 
                           )auto_increment=3 ;
Copy after login

4. Data types supported by MySQL

1. ENUM and SET types

  • The Chinese name of ENUM is called an enumeration type, and its value range requires Displayed via enumeration when creating the table.
    ENUM only allows you to select a single value from a value collection, not multiple values ​​at once. Purpose: Single choice: Select gender

ENUM:
The enumeration of 1-255 members requires 1 byte storage;
For 255-65535 members, Requires 2 bytes of storage;
Allows up to 65535 members.

  • SET is very similar to ENUM. It is also a string object that can contain 0-64 members. Storage varies depending on the member.
    The set type allows any selection of 1 or more elements in the value set for combination. Injection will not be allowed for content that is out of range, and duplicate values ​​will be automatically deduplicated. Usage: Multiple choice: Interests, hobbies, gender

SET:
1-8个成员的集合,占1个字节
9-16个成员的集合,占2个字节
17-24个成员的集合,占3个字节
25-32个成员的集合,占4个字节
33-64个成员的集合,占8个字节

2、set/enum示例

mysql> create table t10 (name char(20),gender enum('female','male') );
Query OK, 0 rows affected (0.01 sec)

-- 选择enum('female','male')中的一项作为gender的值,可以正常插入
mysql> insert into t10 values ('nick','male');
Query OK, 1 row affected (0.00 sec)

-- 不能同时插入'male,female'两个值,也不能插入不属于'male,female'的值
mysql> insert into t10 values ('nick','male,female');
ERROR 1265 (01000): Data truncated for column 'gender' at row 1

mysql> create table t11 (name char(20),hobby set('抽烟','喝酒','烫头','翻车') );
Query OK, 0 rows affected (0.01 sec)

-- 可以任意选择set('抽烟','喝酒','烫头','翻车')中的项,并自带去重功能
mysql> insert into t11 values ('tank','烫头,喝酒,烫头');
Query OK, 1 row affected (0.01 sec)

mysql> select * from t11;
+------+---------------+
| name | hobby        |
+------+---------------+
| tank | 喝酒,烫头     |
+------+---------------+
row in set (0.00 sec)

-- 不能选择不属于set('抽烟','喝酒','烫头','翻车')中的项,
mysql> insert into t11 values ('jason','烫头,翻车,看妹子');
ERROR 1265 (01000): Data truncated for column 'hobby' at row 1
Copy after login

五、MySQL表查询

1、限制查询的记录数(limit)

示例:

SELECT * FROM employee ORDER BY salary DESC 
    LIMIT 3;    --默认初始位置为0 

SELECT * FROM employee ORDER BY salary DESC
    LIMIT 0 , 5 ; --从第0开始,即先出第一条,然后包含这一条在内往后查5条

SELECT * FROM employee ORDER BY salary DESC
    LIMIT 5 , 5 ; --从第5开始,即先出第6条,然后包含这一条在内往后查5条
Copy after login

2、使用正则表达式查询

小结:对字符串匹配的方式

  • WHERE emp_name = 'nick';

  • WHERE emp_name LIKE 'sea%';

  • WHERE emp_name REGEXP 'on$';

SELECT * FROM employee WHERE emp_name REGEXP '^jas';
SELECT * FROM employee WHERE emp_name REGEXP 'on$';
SELECT * FROM employee WHERE emp_name REGEXP 'm{2}';
Copy after login

六、数据备份(命令行)

1、 数据库的逻辑备份

--语法:
mysqldump -h 服务器 -u用户名 -p密码 数据库名 > 备份文件.sql

--示例:
--单库备份
mysqldump -uroot –p123  mysql > c:\db1.sql
mysqldump -uroot -p123 db1 table1 table2 > db1-table1-table2.sql

--多库备份
mysqldump -uroot -p123 --databases db1 db2 mysql db3 > db1_db2_mysql_db3.sql

--备份所有库
mysqldump -uroot -p123 --all-databases > all.sql
Copy after login

2、 数据恢复

--方法一:
[root@nick backup]-- mysql -uroot -p123 < /backup/all.sql

--方法二:
mysql> use db1;
mysql> SET SQL_LOG_BIN=0;   --关闭二进制日志,只对当前session生效
mysql> source /root/db1.sql
Copy after login

七、事务和锁(SQL)

begin;  -- 开启事务
   select * from emp where id = 1 for update;  -- 查询id值,for update添加行锁;
    update emp set salary=10000 where id = 1; -- 完成更新
commit; -- 提交事务
Copy after login

八、执行计划Explain

执行计划:让mysql预估执行操作(一般正确)

Explain语法:

explain select &hellip; from &hellip; [where &hellip;]

Explain命令在解决数据库性能上是第一推荐使用命令,大部分的性能问题可以通过此命令来简单的解决,Explain可以用来查看SQL语句的执行效果,可以帮助选择更好的索引和优化查询语句,写出更好的优化语句。

具体用法和字段含义可以参考官网explain-output ,这里需要强调rows是核心指标,绝大部分rows小的语句执行一定很快(rows:显示MySQL认为它执行查询时必须检查的行数。)。所以优化语句基本上都是在优化rows。

例如:

explain select * from news;
Copy after login

输出:

+--+-----------+-----+----+-------------+---+-------+---+----+-----+ 
|id|select_type|table|type|possible_keys|key|key_len|ref|rows|Extra| 
+--+-----------+-----+----+-------------+---+-------+---+----+----—+
Copy after login

The above is the detailed content of Analysis of basic operation examples of MySQL database. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template