Today, we will share with you the "magic tricks" for optimizing MySQL performance, including optimizing MySQL performance and locking tables, the usage of Foreign keys to optimize MySQL performance is described in detail in the following article.
Optimizing MySQL Performance
Although we can use subqueries Sub-Queries), JOIN joins, and UNION) to create various Queries, however, not all database operations can be completed with only one or a few SQL statements. In more cases, a series of statements are needed to complete some work. However, in this case, when a statement in the statement block fails to run, the operation of the entire statement block becomes uncertain.
Imagine that you want to insert data into two associated tables at the same time. This may happen: after the first table is successfully updated, the database suddenly experienced an unexpected situation, as a result, the operations in the second table are incomplete, which may damage the data in the database. To avoid this situation, you should use a transaction. Its function is to either operate successfully or fail each statement in the statement block.
In other words, data consistency and integrity can be maintained in the database. The transaction starts with the BEGIN keyword and ends with the COMMIT keyword. If an SQL operation fails, the ROLLBACK command can restore the database to the State before the start of in.
- BEGIN;
- INSERT INTO salesinfo SET CustomerID=14;
- UPDATE inventory SET Quantity=11
- WHERE item='book';
- COMMIT;
Another important role of transactions is that when multiple users use the same data source at the same time, they can use the database locking method to provide users with a safe access method, this ensures that user operations are not affected by other users.
Optimize MySQL performance by locking tables
Although transactions are a very good way to maintain database integrity, they sometimes affect database performance, especially in large application systems. Because the data database will be locked during transaction execution, other user requests can only wait until the transaction ends. If a database system is used by only a few users, the impact of transactions will not become a big problem. However, assuming that thousands of users access a database system at the same time, for example, accessing an e-commerce website may cause serious response latency.
In fact, in some cases, we can achieve better performance by locking the table. The following example uses the table locking method to complete the transaction function in the previous example.
- LOCK TABLE inventory WRITE
- SELECT Quantity FROM inventory
- WHEREItem='book';
- ...
- UPDATE inventory SET Quantity=11
- WHEREItem='book';
- UNLOCK TABLES
Here, we use a SELECT statement to retrieve the initial data. Through some calculations, we use the UPDATE statement to UPDATE the new value to the table. The lock table statement containing the WRITE keyword ensures that no other access is allowed to insert, update, or delete the inventory before the unlock tables command is executed.
Using Foreign keys to optimize MySQL Performance
Locking a table can maintain data integrity, but it cannot guarantee data association. In this case, we can use the foreign key. For example, a foreign key can ensure that each sales record points to an existing customer. Here, the foreign key can map the CustomerID in the customerinfo table to the CustomerID in the salesinfo table. No record without a valid CustomerID will be updated or inserted into the salesinfo table.
- CREATE TABLE customerinfo
- (
- CustomerID INT NOT NULL ,
- PRIMARY KEY ( CustomerID )
- ) TYPE = INNODB;
- CREATE TABLE salesinfo
- (
- SalesID INT NOT NULL,
- CustomerID INT NOT NULL,
- PRIMARY KEY(CustomerID, SalesID),
- FOREIGN KEY (CustomerID) REFERENCES customerinfo
- (CustomerID) ON DELETECASCADE
- ) TYPE = INNODB;
Note that the parameter "on delete cascade" is in the subexample ". This parameter ensures that when a customer record in the customerinfo table is deleted, all records related to this customer in the salesinfo table will also be deleted automatically. If you want to use foreign keys in MySQL, remember to define the table type as the InnoDB type of the Transaction Security table when creating the table. This type is not the default MySQL table type. The defined method is to add TYPE = INNODB In the create table statement. As shown in the example.
Using indexes to optimize MySQL Performance
Index is a common method to improve database performance. It allows database servers to retrieve specific rows at a much faster speed than no index, especially when a query statement contains MAX (), when using the MIN () and ORDERBY commands, the performance improvement is more obvious. Which fields should be indexed? In general, the index should be built on the fields that will be used for JOIN, WHERE judgment and order by sorting.
Try not to index a field in the database that contains a large number of repeated values. For an ENUM type field, it is very likely that a large number of repeated values appear, such as "province" in customerinfo ".. it is not helpful to create an index on such a field. On the contrary, it may also reduce the performance of the database. When creating a TABLE, we can CREATE an appropriate INDEX at the same time, or use alter table or create index to CREATE an INDEX later.
MySQL supports full-text indexing and search from version 3.23.23. Full-text index is a FULLTEXT index in MySQL, but it can only be used for tables of the MyISAM type. For a large database, it is very fast to load data to a TABLE without FULLTEXT indexes and then CREATE an INDEX using alter table or create index. However, if you load data to a table with a FULLTEXT index, the execution will be very slow.
Optimization of MySQL Performance
In most cases, using indexes can increase the query speed. However, if an SQL statement is improperly used, indexes cannot play its due role. The following aspects should be noted. First, it is best to compare fields of the same type.
Before MySQL 3.23, this is even a required condition. For example, you cannot compare an indexed INT field with a BIGINT field. However, in special cases, when a CHAR field is of the same size as a VARCHAR field, you can compare them. Second, do not use functions to operate indexed fields.
For example, when the YEAE () function is used on a DATE field, the index cannot play its due role. Therefore, although the two queries below return the same results, the latter is much faster than the former.
- SELECT * FROM order WHERE YEAR(OrderDate)<2001;
- SELECT * FROM order WHERE OrderDate<"2001-01-01";
In the same case, when the numeric field is calculated:
- SELECT * FROM inventory WHERE Amount/7<24;
- SELECT * FROM inventory WHERE Amount<24*7;
The above two queries also return the same results, but the subsequent query will be much faster than the previous one. Third, when searching for a struct field, we sometimes use the LIKE keyword and wildcard. Although this method is simple, it is at the cost of system performance. For example, the following query will compare each record in the table.
- SELECT * FROM books
- WHERE name like "MySQL%"
However, if the following query is used, the returned results will be the same, but the speed will be much faster :..
- SELECT * FROM books
- WHERE name>="MySQL"and name<"MySQM"
Finally, you should note that you should avoid making MySQL automatically convert the data type during the query, because the conversion process also makes the index ineffective.