Summary of the latest MYSQL interview questions in 2023


MYSQL

Introduction:
MySQL database is an open source relational database management system, which supports multi-user, multi-thread, and multiple storage engines, and can run on various operating systems. The advantages of MySQL include open source and free, high performance, stability and reliability, support for multiple operating systems and programming languages, and ease of use and management. The disadvantages of MySQL include limited scalability, some advanced features require an additional paid commercial version, and insufficient security.

1. The storage engine and the difference between

MySQL storage engines include InnoDB, MyISAM, Memory, Archive, CSV, Blackhole, etc. Among them, InnoDB is the default storage engine of MySQL, which supports advanced functions such as transactions, row-level locks, and foreign keys, and is suitable for applications that require high concurrency and high reliability. MyISAM does not support transactions and row-level locks, but it is faster and simpler than InnoDB, and is suitable for applications with a low ratio of reads and writes. The Memory storage engine stores data in memory, and the reading and writing speed is very fast, but it is prone to data loss. The Archive storage engine is suitable for applications that only perform large-scale writes once. The CSV storage engine is used to store data in files in CSV format. Blackhole storage engine receives written data and discards it, suitable for testing and logging

2. Types of MySQL indexes

An index is a data structure used in a database to improve query efficiency. It can sort and organize the data to be queried according to certain rules for quick search. The index types in MySQL include B-Tree index, Hash index, Full-text index, etc. Among them, the B-Tree index is the most commonly used index type in MySQL, which is suitable for searching data with a relatively large range. Hash indexes are suitable for searching tables with a relatively small amount of data. Full-text index is suitable for full-text search of text data

3. Transactions in MySQL

A transaction is an execution sequence of a set of SQL statements, which can ensure the consistency and integrity of data in a concurrent environment. In MySQL, transaction control can be realized through BEGIN, COMMIT and ROLLBACK statements. In a transaction, if any error occurs, you can use the ROLLBACK statement to undo all executed SQL statements and roll back to the state where the transaction started.

4. How to ensure the atomicity of transactions

To ensure the atomicity of transactions, the following principles need to be followed:
ACID principles: In relational databases, the atomicity of transactions needs to follow the ACID principles. ACID stands for Atomicity, Consistency, Isolation and Durability.

Atomicity definition: A transaction is an indivisible sequence of operations, either all of which are executed successfully, or none of them are executed, and partial success and partial failure are not allowed. If an error occurs during transaction execution, all modifications will be rolled back to ensure data consistency.

Rollback mechanism: When an error occurs during the execution of a transaction, a rollback mechanism needs to be used to ensure the atomicity of the transaction. The rollback mechanism refers to undoing all operations in the transaction and returning to the state before the transaction started to ensure data consistency.

Lock mechanism: In a multi-user environment, in order to avoid data conflicts and concurrent access problems, it is necessary to use a lock mechanism to ensure the atomicity of transactions. The lock mechanism refers to locking the data. Only the transaction that acquires the lock can modify the data, and other transactions need to wait for the lock to be released before they can operate.

To sum up, to ensure the atomicity of transactions, it is necessary to follow the ACID principle in database design and programming implementation, define the operation range of transactions, and use the rollback mechanism and lock mechanism to avoid data conflicts and concurrent access problems, so that Ensure transactional consistency and data integrity.

5. Create and use views in MySQL

A view is a virtual table, which is constructed based on the query results of one or more tables, and has the same attributes and structure as a table. In MySQL, views can be created with the CREATE VIEW statement. For example, to create a view named view you can use the following command:

CREATE VIEW view AS SELECT column1, column2 FROM my_table WHERE condition;

When using a view, it can be queried like a normal table, for example:

SELECT * FROM view;

6. Define primary key and foreign key in MySQL

A primary key is a column or column group used to uniquely identify a record, which cannot be repeated in a table. A foreign key is a column in one table, which is associated with the primary key of another table, and is used to establish a relationship between different tables. In MySQL, primary and foreign keys can be defined by adding PRIMARY KEY and FOREIGN KEY to the table definition. For example, to create a table named table1 and define its primary and foreign keys use the following command:

CREATE TABLE table1 (
  id INT NOT NULL AUTO_INCREMENT,
  name VARCHAR(50) NOT NULL,
  PRIMARY KEY (id)
);

CREATE TABLE table2 (
  id INT NOT NULL AUTO_INCREMENT,
  table_id INT NOT NULL,
  FOREIGN KEY (table_id) REFERENCES table1(id),
  PRIMARY KEY (id)
);

7. Data backup and restore

You can use the mysqldump command to back up data in MySQL, for example:

mysqldump -u root -p my_database > my_database_backup.sql

This command will back up the database named my_database and save the backup results in a file named my_database_backup.sql. To restore backup data, you can use the following command:

mysql -u root -p my_database < my_database_backup.sql

8. Performance optimization of MySQL database

The following methods can be used to optimize the performance of the MySQL database:
Use the correct data type and index
Optimize query statements to avoid full table scans Avoid
excessive use
of subqueries Use connection pools to reduce connection overhead
Use partitions to improve data read and write efficiency speed.
Use caching to reduce the number of database visits
. Optimize SQL statements to avoid unnecessary JOIN operations and subqueries.
Adjust MySQL configuration parameters, such as increasing buffer size and thread pool size, etc.

9. Create a stored procedure in MySQL

Open the MySQL command line client and connect to your database server.

To create a new stored procedure, use the CREATE PROCEDURE statement and specify the stored procedure name. For example, here is sample code to create a stored procedure called "get_customers":

CREATE PROCEDURE get_customers()
BEGIN
  SELECT * FROM customers;
END

Write the code for the stored procedure between the BEGIN and END keywords. For instance, in the example above we just selected all the rows from the table called "customers".

Use the DELIMITER statement to set a new delimiter. By default, a semicolon (;) is used to separate each SQL statement, but stored procedures themselves contain semicolons as well. Therefore, you need to change the delimiter to another character such as "$$".

DELIMITER $$

After the new delimiter, write the CREATE PROCEDURE statement and stored procedure code. At the end of the stored procedure, end the stored procedure with the new delimiter.

CREATE PROCEDURE get_customers()
BEGIN
  SELECT * FROM customers;
END$$

Finally, execute the CREATE PROCEDURE statement to add the stored procedure to the database.

CREATE PROCEDURE get_customers()
BEGIN
  SELECT * FROM customers;
END$$

Successfully created a simple MySQL stored procedure. To run a stored procedure, use the CALL statement:

CALL get_customers();

This will execute the get_customers stored procedure and return the result.

10. Create and use triggers

Triggers can be used in MySQL to automatically execute some operations on specified tables, such as automatically executing certain logic when inserting, updating, and deleting records, and so on. Here are the basic steps to create and use a trigger:

Create a trigger
In MySQL, use the CREATE TRIGGER statement to create a trigger, the syntax is as follows:

CREATE TRIGGER trigger_name
trigger_time trigger_event ON table_name
FOR EACH ROW
BEGIN
    -- 触发器的操作逻辑
END;

Among them, trigger_name is the name of the trigger, trigger_time is the trigger time, including BEFORE and AFTER, respectively indicating that the trigger is executed before or after the statement is executed; trigger_event is the trigger event, including INSERT, UPDATE and DELETE, respectively indicating that the trigger is inserted, updated or deleted Execute the trigger when recording; table_name is the name of the table that needs the trigger; FOR EACH ROW means to execute the operation logic of the trigger for each row of records.

Write the operation logic of the trigger
Write the operation logic that needs to be executed between BEGIN and END of the trigger, such as inserting, updating, deleting records, and so on. In operation logic, NEW and OLD keywords can be used to refer to records before and after insertion, update or deletion. For example, NEW.column_name indicates the column value after insertion or update, and OLD.column_name indicates the column value before update or deletion.

Using triggers
After creating a trigger, you can insert, update or delete records on the table that needs to be operated, and the trigger will automatically execute the corresponding operation logic.

For example, the following creates a trigger on the orders table that automatically sets the created_at column to the current time when a record is inserted:

CREATE TRIGGER set_created_at
BEFORE INSERT ON orders
FOR EACH ROW
BEGIN
    SET NEW.created_at = NOW();
END;

When using triggers, you need to pay attention to the following points:

Triggers are associated with tables, so when deleting a table, you need to delete the related triggers first.
Triggers can be deleted using the DROP TRIGGER statement.
Triggers You can use the SHOW TRIGGERS statement to view a list of triggers in the current database.

11. MySQL paging query

In MySQL, you can use the LIMIT statement to implement paging queries. For example, to query the data on page 3 of the table named my_table and display 10 records per page, you can use the following command:

SELECT * FROM my_table LIMIT 20, 10;

This command will query from the 21st record and query 10 records.

12. Using MySQL transactions

In MySQL, you can use BEGIN, COMMIT, and ROLLBACK statements to process transactions. They must be executed together in the database and either all succeed or all fail. For example, here's an example using transactions:

BEGIN;
INSERT INTO my_table (column1, column2) VALUES (value1, value2);
UPDATE my_table2 SET column3 = value3 WHERE condition;
COMMIT;

This example will start a transaction, execute an INSERT statement and an UPDATE statement, and if both statements succeed, commit the transaction, otherwise rollback the transaction and undo all changes.

13. MySQL performs data type conversion

In MySQL, you can use the CAST or CONVERT function to convert data types. For example, to convert a value of type string to integer type use the following command:

SELECT CAST('123' AS SIGNED);

This command converts the string '123' to an integer type.

14. MySQL performs string operations

In MySQL, you can use functions such as CONCAT, SUBSTRING, REPLACE, and LOWER to perform string operations. For example, to concatenate two strings you can use the following command:

SELECT CONCAT('hello', 'world');

This command concatenates the strings 'hello' and 'world' and returns 'helloworld'.

15. MySQL date and time operations

Get the current date and time:

SELECT NOW();   -- 返回当前日期和时间
SELECT CURDATE();   -- 返回当前日期
SELECT CURTIME();   -- 返回当前时间

Date and time calculations:

SELECT DATE_ADD('2023-01-01', INTERVAL 1 YEAR);   -- 返回2024-01-01
SELECT DATE_SUB('2023-01-01', INTERVAL 1 MONTH);   -- 返回2022-12-01
SELECT ADDTIME('12:00:00', '01:00:00');   -- 返回13:00:00
SELECT SUBTIME('12:00:00', '01:00:00');   -- 返回11:00:00

Format date and time:

SELECT DATE_FORMAT('2023-04-07', '%Y-%m-%d');   -- 返回2023-04-07
SELECT TIME_FORMAT('12:30:00', '%h:%i %p');   -- 返回12:30 PM

Compare dates and times:

SELECT '2023-04-07' < '2023-05-01';   -- 返回1(真)
SELECT '12:00:00' > '11:00:00';   -- 返回1(真)

Extract the date and time parts:

SELECT YEAR('2023-04-07');   -- 返回2023
SELECT MONTH('2023-04-07');   -- 返回4
SELECT DAY('2023-04-07');   -- 返回7
SELECT HOUR('12:30:00');   -- 返回12
SELECT MINUTE('12:30:00');   -- 返回30
SELECT SECOND('12:30:00');   -- 返回0

These are some basic date and time operations, and MySQL also provides other functions and operators to support more complex date and time calculations and manipulations.

16.MySQL index optimization

In MySQL, indexes can be used to improve query performance. An index is a data structure that speeds up lookups in a database. In MySQL, you can use the CREATE INDEX statement to create an index, for example:

CREATE INDEX my_index ON my_table (column1, column2);

This command will create an index named my_index on the table named my_table with columns column1 and column2.

17. Use MySQL for backup and recovery
In MySQL, you can use the mysqldump command to back up the database, for example:

mysqldump -u username -p password my_database > backup.sql

This command will back up the database named my_database and save the backup data to the backup.sql file. To restore the database, the following command can be used:

mysql -u username -p password my_database < backup.sql

This command will restore the database from the backup.sql file.

18.MySQL High Availability and Fault Tolerance

In MySQL, the following methods can be used to achieve high availability and fault tolerance:
use master-slave replication to realize off-site data backup and read-write separation.
Use clusters to implement distributed storage and load balancing of data.
Use multiple instances to increase the reliability and fault tolerance of your system.
Use automatic failover for high availability and fault tolerance.
Use backup and recovery strategies to avoid data loss and corruption.

19. MySQL security management

In MySQL, the following methods can be used to ensure the security of the database:
Use access control to limit the user's authority and access scope.
Use protocols such as SSL and TLS to encrypt the communication process of the database.
Use firewalls and network security devices to ensure database network security.
Regularly back up data and log files to avoid data loss and damage.
Use password policies to ensure user account security, such as setting the complexity and expiration date of passwords.

20. Lock processing in
MySQL In MySQL, the following statements can be used for lock processing:
shared lock: SELECT ... FOR SHARE command will lock the queried rows during the execution of the SELECT statement, other transactions can read these rows, but not Modify them.
Exclusive lock: The SELECT ... FOR UPDATE command will lock the queried rows during the execution of the SELECT statement and prevent other transactions from reading or modifying these rows.
Row-level locks: In the MySQL InnoDB storage engine, you can use the SELECT ... FOR UPDATE and SELECT ... FOR SHARE commands to implement row-level locks.

21.MySQL monitoring and diagnosis
In MySQL, you can use the following tools for monitoring and diagnosis:
MySQL Enterprise Monitor: This is a commercial MySQL monitoring and management tool that can monitor the performance and health status of MySQL in real time.
MySQL Workbench: This is a free MySQL administration tool that enables performance analysis and diagnostics.
MySQL Performance Schema: This is a performance analysis tool provided by MySQL, which can analyze query performance and system resource utilization.
MySQL Slow Query Log: This is MySQL's slow query log, which can record SQL statements whose execution time exceeds the threshold to help analyze performance bottlenecks.

22. Performance testing in
MySQL In MySQL, you can use the following tools for performance testing:
sysbench: This is a commonly used MySQL performance testing tool that can simulate multiple clients accessing the database at the same time.
mysqlslap: This is a MySQL performance testing tool that can simulate multiple clients executing SQL statements concurrently.
pt-query-digest: This tool can analyze MySQL query logs, find slow queries and frequently executed queries, and provide optimization suggestions.

Guess you like

Origin blog.csdn.net/weixin_43749805/article/details/130009611