MySQL database management - user management (2)

Article Directory

1. Table structure (add fields)

1. Create a table structure

use sky;
#指定主键的第二种方式
create table if not exists sky (id int(4) zerofill primary key auto_increment,name varchar(10) not null,cardid int(18) not null unique key,hobby varchar(50));
desc sky;

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-2XsYpFJW-1689217969056) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230712162630420.png)]

Notes:

#if not exists: Indicates to check whether the table to be created already exists, and if it does not exist, continue to create
#int(4) zerofill: Indicates that if the value is less than 4 digits, it will be filled with "0", for example 0001
#auto_increment: Indicates that this field is a self-increasing field, that is, each record is automatically incremented by 1, and the increment starts from 1 by default;

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-OJryJOuI-1689217969057) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230712164910731.png)]

The self-growth field data cannot be repeated; the self-growth field must be the primary key; if the added record data does not specify the value of this field, it will automatically increment once if the addition fails (this is the
imported data will be inserted next to the next in the table) #unique key: Indicates the unique key constraint of this field, and the data in this field cannot be repeated: there can only be one primary key in a table, but there can be multiple unique keys in a table #not null: Indicates that this field is not allowed to
be
NULL

2. Copy the data table

2.1 Copy format

(1) format

create table 生成新的表名 like 复制的表名; 

(2) Example

#复制格式,通过LIKE方法,复制sky表结构生成sun表
create table sun like sky;
#查看库中的表
show tables;

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-5IIiTPhR-1689217969058) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230712175951893.png)]

#备份内容
insert into sun select * from sky;
desc sun;
select * from sun;

[External link image transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the image and upload it directly (img-IuC86Mln-1689217969058) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230712180246412.png)]

2.2 Clone table

Generate the data records of the data table into a new table

(1) format

CREATE TABLE 需要创建的新表(select * from 已存在需要新表复制的数据的表);

(2) Example

#复制test 表数据到test02中
create table banana (select * from sky);
#获取数据表的表结构、索引等信息
show create table banana\G;
select * from banana;
desc banana;

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-Lrm4b1EP-1689217969059) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230712181621515.png)]

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-IlX7RTuT-1689217969059) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230712181636674.png)]

3. Clear the table and delete all data in the table

(1) Method 1:

#DELETE清空表后,返回的结果内有删除的记录条目; 
delete from banana;
show tables;
desc banana;
select from * banana;

When DELETE works, it deletes record data line by line; if there are self-incrementing fields in the table, after using DELETE FROM to delete all records, the newly added record will continue to self-increment and write records from the original largest record ID. This delete just deletes the data in the table

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-bWhTbxsZ-1689217969059) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230712182345921.png)]

Newly added records will continue to auto-increment and write records from behind the original largest record ID

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-E4MShs3s-1689217969060) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230712183957188.png)]

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-WPTesInX-1689217969060) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230712184056333.png)]

(2) Method 2:

#TRUNCATE清空表后,没有返回被删除的条目:
truncate table sun;

When TRUNCATE works, the table structure is re-established as it is, so TRUNCATE will be faster than DELETE to clear the table; after using TRUNCATE TABLE to clear the data in the table, the ID will be re-recorded from 1

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-t3EHMUja-1689217969060) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230712184322376.png)]

4. Create a temporary table

After the temporary table is successfully created, the created temporary table cannot be seen by using the SHOWTABLES command, and the temporary table will be destroyed after the connection exits.
Before exiting the connection, you can also perform operations such as adding, deleting, modifying and checking, such as using the DROP TABLE statement to manually delete the temporary table directly.
PS: foreign keys cannot be created

(1) format

CREATE TEMPORARY TABLE 表名 (字段1 数据类型,字段2 数据类型[, ...][, PRIMARY KEY (主键名)]);

(2) Example:

create temporary table tree (id int(4) zerofill primary key auto_increment,name varchar(10) not null,cardid int(18) not null unique key,hobby varchar(10));

insert into tree values (1,'qqq',123456,'running') ;
select * from tree;
show tables;
quit
select * from tree;

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-id2nGZqX-1689217969061) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230712185028542.png)]

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-qdsJ5rlQ-1689217969061) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230712185217780.png)]

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-PoWeHnEu-1689217969062) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230712185315776.png)]

(3) Application scenarios

  • Can be used in a test environment, such as when deleting a large amount of data, you can create a temporary table to do a complex delete
  • The requirement is to register all the new numbers of a certain software today

2. Six common constraints in MySQL

Primary key constraint (primary key)
foreign key constraint (foreign key)
non-null constraint (not null)
unique constraint (unique [key|index])
default value constraint (default)
self-increment constraint (auto_increment)

1. Definition of foreign key

If the same attribute field x is the primary key in table 1 but not in table 2, the field x is called the foreign key of table 2.

2. Create foreign key constraints

Create foreign key constraints (accidental deletion, modification) to ensure data integrity and consistency.
Understanding of primary key tables and foreign key tables
(1) Tables with public keywords as primary keys are primary key tables (parent table, primary table)
(2) Tables with public keywords as foreign keys are foreign key tables (slave tables, foreign tables)
Note: The fields of the primary table associated with foreign keys must be set as primary keys. It is required that the slave table cannot be a temporary table, and
the foreign key fields of the master table and the fields of the slave table have the same data type, character length and constraints.

3. Create the main table blue

create table blue (hobid int(4),hobname varchar(50));

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-nskc0gNL-1689217969062) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230712185720718.png)]

4. Create a table from Icecream

create table Icecream(id int(4) primary key auto_increment,name varchar(10),age int(3),hobid int(4));

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-eUozVqcJ-1689217969062) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230712190501221.png)]

5. Add a primary key constraint to the main table blue. The primary key name is recommended to start with "PK_".

alter table blue add constraint PK_hobid primary key (hobid);

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-L8LjKchi-1689217969063) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230712190836803.png)]

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-rW6HN5MC-1689217969064) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230712191002558.png)]

6. Add a foreign key to the slave table Icecream table, and establish a foreign key association between the hobid field of the Icecream table and the hobid field of the blue table.

It is recommended to start the foreign key name with "FK_".

alter table Icecream add constraint FK_hob foreign key (hobid) references blue (hobid);

7. You can use the query table statement structure command to view foreign key associations

show create table Icecream;
desc blue;
desc Icecream;

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-v2Pow1se-1689217969064) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230712191911095.png)]

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-340bffuh-1689217969065) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230712191750233.png)]

In the MySQL database, MULit is KEYa type of and the full name is MULTIPLE, which means multiple indexes.

When there are multiple columns in the table that form the index, each index column will display MULthe type. This usually happens when CREATE INDEXa multi-column composite index is defined using .

MULThe type has two meanings: one means that the current index column contains multiple identical values, that is, duplicate values, and the other means that the current index column contains multiple different values, that is, non-unique values.

It should be noted that if the type of an index column is MUL, there may be performance problems when using queries, because MySQL cannot determine which values ​​are unique on all index columns, which will cause MySQL to read more data and perform more complex query operations.

If you need to optimize query performance, you can try to use EXPLAINthe command or redesign the table structure and merge indexes to improve index efficiency.

8. When inserting a new data record, the master table and then the slave table must be inserted

insert into blue values(1,'running');
insert into Icecream values(1,'zs',18,1);

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-qF59irBX-1689217969065) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230712192901632.png)]

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-c1j2xjpa-1689217969066) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230712192932122.png)]

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-eMq9Fduf-1689217969066) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230712193111402.png)]

9. When deleting data records, you must first delete the table and then the main table, that is to say, when deleting the primary key table, you must first delete other tables associated with it.

drop tables Icecream;
drop tables blue;

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-XuXowzg3-1689217969067) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230712193252523.png)]

10. View and delete foreign key constraints

#如果要删除外键约束字段先删除外键约束,再删除外键名
show create table Icecream;
alter table Icecream drop foreign key FK_hob;
alter table Icecream drop key FK_hob;
desc Icecream;

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-8iHhtfYH-1689217969067) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230712193904435.png)]

3. Database user management

1. Create a new user

(1) format

CREATE USER '用户名'@'来源地址' [IDENTIFIED BY [PASSWORD] '密码'];

'Username': Specify the username to be created.
'Source address': Specify which hosts the newly created user can log in on, using the form of IP address, network segment, and hostname. Local users can use localhost, allowing any host to log in. Wildcards %'password': If you use a plaintext password, directly enter 'password', which will be automatically encrypted by Mysql when inserted into the database; if you use an encrypted password, you need to use SELECT PASSWORD('password'); 'Ciphertext'; if the "IDENTIFIED BY" part is omitted, the user's password will be empty
(
not
recommended
)

(2) Example

#明文创建
create user 'user1'@'localhost' identified by '123456';
#密文创建
select password('abc123');
create user 'user2'@'localhost' identified by password '*6691484EA6B50DDDE1926A220DA01FA9E575C18A';

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-8KSV14nV-1689217969068) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230712194544848.png)]

2. View user information

The created user is saved in the user table of the mysql database

USE mysql;
SELECT User,authentication_string,Host from user;

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-BPiEfv5b-1689217969068) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230712194723270.png)]

3. Multiple naming specification

rename user 'user1'@'localhost' to 'lisi'@'localhost';
SELECT User,authentication_string,Host from user;

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-xYWML6N4-1689217969068) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230713084321398.png)]

4. Delete user

DROP USER 'lisi'@'localhost' ;

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-Zo1LGHwk-1689217969070) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230713084425726.png)]

5. Modify the current password

SET PASSWORD = PASSWORD('abc123');

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-hzOaEKaw-1689217969070) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230713084634712.png)]

6. Modify other user passwords

set password for 'user2'@'localhost' = password('123456');

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-OD7bHwhY-1689217969071) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230713085105698.png)]

7. Forget the root password solution

修改/etc/my.cnf 配置文件,免密登陆mysql
vim /etc/my.cnf
[mysqld]
#添加,使登录mysql不使用授权表
skip-grant-tables    

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-ou3LlOGK-1689217969071) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230713085520514.png)]

systemctl restart mysqld
mysql    #直接登录

[External link image transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the image and upload it directly (img-1jGWTPed-1689217969071) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230713085626484.png)]

然后使用SQL语句修改密码
UPDATE mysql.user SET AUTHENTICATION_STRING = PASSWORD('abc123') where user='root';
#刷新,必须大写
FLUSH PRIVILEGES;
quit
mysql -u root -pabc123
PS:最后再把/etc/my.cnf 配置文件里的skip-grant-tables 删除,并重启mysql服务,即取消免密登录数据库

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-zt5itgJk-1689217969072) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230713090123219.png)]

4. Database user authorization

1. Grant permissions

grant Elevation of rights

(1) format

GRANT 权限列表 ON 数据库名.表名 TO '用户名'@'来源地址' [IDENTIFIED BY '密码'];

(2) Example

#授权了一个名为 'user2' 的 MySQL 用户对所有数据库和表拥有全部权限
grant all privileges on *.* to 'user2'@'%' identified by '123456';
Query OK, 0 rows affected, 1 warning (0.00 sec)

#Permission list: used to list various database operations authorized to use, separated by commas, such as "select, insert,
update". Use "all" for all permissions, which grants permission to perform any action.

#Database name.Table name: The name of the database and table used to specify the authorization operation, where the wildcard " " can be used.
For example, use "kgc.
" to indicate that the objects of the authorized operation are all tables in the school database.

#'User name@source address': used to specify the user name and the client address allowed to access, that is, who can connect and from where. The source address can be a domain name, an IP address, and a "%" wildcard can be used to represent all addresses in a certain area or network segment, such as "%.xyw.com", "192.168.80.%", etc.

#IDENTIFIED BY: Used to set the password string used by the user to connect to the database.
When creating a new user, if the "IDENTIFIED BY" part is omitted, the user's password will be empty.

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-YUI29KWn-1689217969072) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230713091450820.png)]

Order meaning
grant The keyword of the authorization operation in the SQL statement, which means granting the user specific access rights.
all privileges System permission keyword, which means granting all permissions to the user.
on . Database-related statements, indicating that all databases and user tables are specified.
to ‘user2’@‘%’ A user specification statement that grants authority to a user named 'user2' and that user can log in from any host %.
identified by ‘123456’ The user specified statement indicates that the login password of the user 'user2' is '123456'.

2. A user is allowed to query the data records of all tables in a database locally, but is prohibited from querying the records of tables in other databases.

grant select on banana.* to 'ff'@'localhost' identified by '123456';
Query OK, 0 rows affected, 2 warnings (0.00 sec)

3. Allow a user to remotely connect to mysql in all terminals and have all permissions.

grant all privileges on *.* to 'zjf'@'%' identified by '123456';
Query OK, 0 rows affected, 1 warning (0.00 sec)
#刷新权限
flush privileges;    
quit

test

mysql -u zjf -p123456
show databases;
use summer;
show tables; .
select * from sun;

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-Mk0Wpxvj-1689217969072) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230713102551700.png)]

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-NSrKXX1Z-1689217969073) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230713102750268.png)]

delete from sky;

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-hvlxe2yX-1689217969073) (C:\Users\zhao\AppData\Roaming\Typora\typora-user-images\image-20230713105842067.png)]

White terminal test connection available
insert image description here
insert image description here

4. View database permissions

mysql -u root -pabc123
SHOW GRANTS FOR 用户名@来源地址;
SHOW GRANTS FOR 'zjf'@'%';

insert image description here

5. Revoke database privileges

(1) format

REVOKE 权限列表 ON 数据库名.表名 FROM 用户名@来源地址;

(2) Example

mysql -u root -pabc123
use mysql;
REVOKE ALL ON *.* FROM 'zjf'@'%'
mysql -uzjf -p123456
SHOW GRANTS FOR 'zjf'@'%';

#USAGE permission can only be used for database login, and cannot perform any operations; USAGE permission cannot be revoked, that is, REVOKE cannot delete users.
flush privileges;
insert image description here

total

1. The difference between drop, truncate and delete in the database

1.1 drop

(1) format

drop table table_name

(2) Features

  • delete fast
  • table and content and structure deletion
  • Can't bring where
  • non-rollback (unrecoverable)
  • belongs to DDL

1.2 truncate

(1) format

truncate table table_name

(2) Features

  • delete fast
  • Delete the contents of the table
  • Can't bring where
  • non-rollback (unrecoverable)
  • belongs to DDL

1.3 delete

(1) format

delete from table_name

(2) Features

  • The deletion is slow and needs to be deleted line by line
  • The table structure is here, and the table content depends on the execution of where
  • can take where
  • Can be rolled back (recoverable)
  • belongs to DML

1.4 Selection in Application Scenarios

  • Use drop when a table is no longer needed
  • When you want to delete some data rows, use delete and add the where clause
  • Use truncate when retaining the table and deleting all data

2. What permissions does the authorized user permission all privileges represent?

insert (insert data)
select (query data)
update (update table data)
delete (delete data in the table)
drop (delete library and table)
cerate (create library, table)
index (create index)
alter (change table attributes)
create view (create view)
create routine (create stored procedure)
alter routine (modify stored procedure)
event (event)

Guess you like

Origin blog.csdn.net/Katie_ff/article/details/131698258