Home Database Mysql Tutorial Take a look at MySQL database advanced operations

Take a look at MySQL database advanced operations

Jan 29, 2021 am 09:18 AM
mysql

Take a look at MySQL database advanced operations

Free learning recommendations: mysql video tutorial

Article Directory

  • Advanced operations on data tables
    • Preparation: Install MySQL database
  • 1. Clone table
    • Method 1
    • Method 2
  • 2. Clear the table and delete all data in the table
    • Method one
    • Method two
  • 3. Create a temporary table
  • 4. Create a foreign key constraint
    • 6 common constraints in MySQL
  • 5. Database user management
    • 1. Create new user
    • 2. View user information
    • 3. Rename user
    • 4. Delete user
    • 5. Modify current login user password
    • 6. Modify Other user passwords
    • 7. Solutions for forgetting the root password
  • 6. Database user authorization
    • 1. Grant permissions
    • 2. View permissions
    • 3. Revoke permissions

##Advanced data table operations

Preparation: Install MySQL database

Shell script one-click deployment - source code compilation and installation of MySQL

create database CLASS;
use CLASS;

create table TEST (id int not null,name char(20) 	not null,cardid varchar(18) not null unique 	key,primary key (id));

insert into TEST(id,name,cardid) values (1,'zhangsan','123123');

insert into TEST(id,name,cardid) values (2,'lisi','1231231');

insert into TEST(id,name,cardid) values (3,'wangwu','12312312');
select * from TEST;
Copy after login

Take a look at MySQL database advanced operations


1. Clone the table

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

Method 1

例:create table TEST01 like TEST;
select * from TEST01;

desc TEST01;
insert into TEST01 select * from TEST;
select * from TEST01;
Copy after login

Take a look at MySQL database advanced operations

Method 2

例:create table TEST02 (select * from TEST);
select * from TEST02;
Copy after login

Take a look at MySQL database advanced operations

2. Clear the table and delete all entries in the table Data

Method 1

delete from TEST02;
Copy after login
#After DELETE clears the table, the returned result contains deleted record entries; DELETE works row by row Deleting record data; if there are self-increasing fields in the table, after using DELETE FROM to delete all records, the newly added records will continue to increment and write records from the original largest record ID

Take a look at MySQL database advanced operations

例:create table if not exists TEST03 (id int primary 	key auto_increment,name varchar(20) not null,cardid varchar(18) not null unique key);
show tables;

insert into TEST03 (name,cardid) values ('zhangsan','11111');		
select * from TEST03;
delete from TEST03;

insert into TEST03 (name,cardid) values ('lisi','22222');
select * from TEST03;
Copy after login

Take a look at MySQL database advanced operations

Method 2

例:select * from TEST03;
truncate table TEST03;
insert into TEST03 (name,cardid) values ('wangwu','33333');
select * from TEST03;
Copy after login
#TRUNCATE After clearing the table, no deleted entries are returned; When TRUNCATE works, the table structure is re-established as it is, so TRUNCATE will clear the table faster than DELETE in terms of speed; after using TRUNCATE TABLE to clear the data in the table, the ID will be recorded again from 1.

Take a look at MySQL database advanced operations


3. Create a temporary table

After the temporary table is successfully created, use SHOW TABLES The command cannot see the temporary table created, and the temporary table will be destroyed after the connection exits. If before exiting the connection, you can also perform operations such as addition, deletion, modification, and query, such as using the DROP TABLE statement to manually delete the temporary table directly.

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

例:create temporary table TEST04 (id int not null,name varchar(20) not null,cardid varchar(18) not null unique key,primary key (id));
show tables;

insert into TEST04 values (1,'haha','12345');	
select * from TEST04;
Copy after login

Take a look at MySQL database advanced operationsTake a look at MySQL database advanced operations

4. Create foreign key constraints

Ensure data integrity and consistency

Definition of foreign key: If the same attribute field x is the primary key in table one but not the primary key in table two, then field x is called the foreign key of table two.

Understanding of primary key tables and foreign key tables:

1. Tables with public keywords as primary keys are primary key tables (parent tables, primary tables)
2. Use public keywords as foreign keys The table is a foreign key table (slave table, external table)

Note: The fields of the master table associated with the foreign key must be set as the primary key. It is required that the slave table cannot be a temporary table, and the fields of the master and slave tables have the same Data type, character length and constraints

例:create table TEST04 (hobid int(4),hobname varchar(50));
create table TEST05 (id int(4) primary key auto_increment,name varchar(50),age int(4),hobid int(4));

alter table TEST04 add constraint PK_hobid primary key(hobid);
alter table TEST05 add constraint FK_hobid foreign key(hobid) references TEST04(hobid);
Copy after login

Take a look at MySQL database advanced operations

例:添加数据记录
insert into TEST05 values (1,'zhangsan','20',1);
insert into TEST04 values (1,'sleep');
insert into TEST05 values (1,'zhangsan',20,1);
Copy after login

Take a look at MySQL database advanced operations

例:drop table TEST04;
drop table TEST05;
drop table TEST04;
Copy after login

Take a look at MySQL database advanced operations
Note: If you want to delete the foreign key Constraint field
Delete the foreign key constraint first, and then delete the foreign key name. This is not demonstrated here

show create table TEST05;
alter table TEST05 drop foreign key FK_hobid;
alter table TEST05 drop key FK_hobid;
desc TEST05;
Copy after login

6 common constraints in MySQL

主键约束 primary key
外键约束 foreign key
非空约束 not null
唯一约束 unique [key
默认值约束 default
自增约束 auto_increment

五、数据库用户管理

1、新建用户

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

‘用户名’:指定将创建的用户名

‘来源地址’:指定新创建的用户可在哪些主机上登录,可使用IP地址、网段、主机名的形式,本地用户可用localhost,允许任意主机登录可用通配符%

‘密码’:若使用明文密码,直接输入’密码’,插入到数据库时由Mysql自动加密;
------若使用加密密码,需要先使用SELECT PASSWORD(‘密码’); 获取密文,再在语句中添加 PASSWORD ‘密文’;
------若省略“IDENTIFIED BY”部分,则用户的密码将为空(不建议使用)

例:create user 'zhangsan'@'localhost' identified by '123123';
select password('123123');
create user 'lisi'@'localhost' identified by password '*E56A114692FE0DE073F9A1DD68A00EEB9703F3F1';
Copy after login

Take a look at MySQL database advanced operations


2、查看用户信息

创建后的用户保存在 mysql 数据库的 user 表里

USE mysql;
SELECT User,authentication_string,Host from user;
Copy after login

Take a look at MySQL database advanced operations

3、重命名用户

RENAME USER 'zhangsan'@'localhost' TO 'wangwu'@'localhost';
SELECT User,authentication_string,Host from user;
Copy after login

Take a look at MySQL database advanced operations

4、删除用户

DROP USER 'lisi'@'localhost';
SELECT User,authentication_string,Host from user;
Copy after login

Take a look at MySQL database advanced operations

5、修改当前登录用户密码

SET PASSWORD = PASSWORD('abc123');
quit
mysql -u root -p
Copy after login

Take a look at MySQL database advanced operations

6、修改其他用户密码

SET PASSWORD FOR 'wangwu'@'localhost' = PASSWORD('abc123');
use mysql;
SELECT User,authentication_string,Host from user;
Copy after login

7、忘记 root 密码的解决办法

1、修改 /etc/my.cnf 配置文件,不使用密码直接登录到 mysql

vim /etc/my.cnf
[mysqld]
skip-grant-tables					#添加,使登录mysql不使用授权表
systemctl restart mysqld
mysql								#直接登录
Copy after login

Take a look at MySQL database advanced operations
Take a look at MySQL database advanced operations

2、使用 update 修改 root 密码,刷新数据库

UPDATE mysql.user SET AUTHENTICATION_STRING = PASSWORD('112233') where user='root';
FLUSH PRIVILEGES;
quit

再把 /etc/my.cnf 配置文件里的 skip-grant-tables 删除,并重启 mysql 服务。
mysql -u root -p
112233
Copy after login

Take a look at MySQL database advanced operations

六、数据库用户授权

1、授予权限

GRANT语句:专门用来设置数据库用户的访问权限。当指定的用户名不存在时,GRANT语句将会创建新的用户;当指定的用户名存在时,GRANT 语句用于修改用户信息。

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

#权限列表:用于列出授权使用的各种数据库操作,以逗号进行分隔,如“select,insert,update”。使用“all”表示所有权限,可授权执行任何操作。

#数据库名.表名:用于指定授权操作的数据库和表的名称,其中可以使用通配符“*”。*例如,使用“kgc.*”表示授权操作的对象为 kgc数据库中的所有表。

#'用户名@来源地址':用于指定用户名称和允许访问的客户机地址,即谁能连接、能从哪里连接。来源地址可以是域名、IP 地址,还可以使用“%”通配符,表示某个区域或网段内的所有地址,如“%.lic.com”、“192.168.184.%”等。

#IDENTIFIED BY:用于设置用户连接数据库时所使用的密码字符串。在新建用户时,若省略“IDENTIFIED BY”部分, 则用户的密码将为空。
Copy after login

#允许用户wangwu在本地查询 CLASS 数据库中所有表的数据记录,但禁止查询其他数据库中的表的记录。

例:
GRANT select ON CLASS.* TO 'wangwu'@'localhost' IDENTIFIED BY '123456';
quit;
mysql -u wangwu -p
123456
show databases;
use information_schema;
show tables;
select * from INNODB_SYS_TABLESTATS;
Copy after login

#允许用户wangwu在本地远程连接 mysql ,并拥有所有权限。

quit;
mysql -u root -p112233
GRANT ALL PRIVILEGES ON *.* TO 'wangwu'@'localhost' IDENTIFIED BY '123456';

flush privileges;
quit

mysql -u wangwu -p123456
create database SCHOOL;
Copy after login

2、查看权限

SHOW GRANTS FOR 用户名@来源地址;

例:
SHOW GRANTS FOR 'wangwu'@'localhost';
Copy after login

3、撤销权限

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

例:quit;
mysql -u root -p112233
SHOW GRANTS FOR 'wangwu'@'localhost';
REVOKE SELECT ON "CLASS".* FROM 'wangwu'@'localhost';

SHOW GRANTS FOR 'wangwu'@'localhost';
Copy after login

#USAGE权限只能用于数据库登陆,不能执行任何操作;USAGE权限不能被回收,即 REVOKE 不能删除用户。

flush privileges;
Copy after login

更多相关免费学习推荐:mysql教程(视频)

The above is the detailed content of Take a look at MySQL database advanced operations. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to open phpmyadmin How to open phpmyadmin Apr 10, 2025 pm 10:51 PM

You can open phpMyAdmin through the following steps: 1. Log in to the website control panel; 2. Find and click the phpMyAdmin icon; 3. Enter MySQL credentials; 4. Click "Login".

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

How to use single threaded redis How to use single threaded redis Apr 10, 2025 pm 07:12 PM

Redis uses a single threaded architecture to provide high performance, simplicity, and consistency. It utilizes I/O multiplexing, event loops, non-blocking I/O, and shared memory to improve concurrency, but with limitations of concurrency limitations, single point of failure, and unsuitable for write-intensive workloads.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

How to connect to the database of apache How to connect to the database of apache Apr 13, 2025 pm 01:03 PM

Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.

How to view sql database error How to view sql database error Apr 10, 2025 pm 12:09 PM

The methods for viewing SQL database errors are: 1. View error messages directly; 2. Use SHOW ERRORS and SHOW WARNINGS commands; 3. Access the error log; 4. Use error codes to find the cause of the error; 5. Check the database connection and query syntax; 6. Use debugging tools.

Monitor Redis Droplet with Redis Exporter Service Monitor Redis Droplet with Redis Exporter Service Apr 10, 2025 pm 01:36 PM

Effective monitoring of Redis databases is critical to maintaining optimal performance, identifying potential bottlenecks, and ensuring overall system reliability. Redis Exporter Service is a powerful utility designed to monitor Redis databases using Prometheus. This tutorial will guide you through the complete setup and configuration of Redis Exporter Service, ensuring you seamlessly build monitoring solutions. By studying this tutorial, you will achieve fully operational monitoring settings

See all articles