search
HomeDatabaseMysql Tutorialmysql——delete syntax

mysql——delete syntax

Nov 23, 2016 am 10:30 AM
deletemysql

Single table syntax:

DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROM tbl_name
    [WHERE where_definition]
    [ORDER BY ...]
    [LIMIT row_count]

Multiple table syntax:

DELETE [LOW_PRIORITY] [QUICK] [IGNORE]
    tbl_name[.*] [, tbl_name[.*] ...]
    FROM table_references
    [WHERE where_definition]

or:

DELETE [LOW_PRIORITY] [QUICK] [IGNORE]
    FROM tbl_name[.*] [, tbl_name[.*] ...]
    USING table_references
    [WHERE where_definition]

Some rows in tbl_name satisfy the conditions given by where_definition. DELETE is used to delete these rows and returns the number of deleted records.

If you write a DELETE statement without a WHERE clause, all rows will be deleted. When you don't want to know the number of deleted rows, there is a faster way, which is to use TRUNCATE TABLE.

If the row you delete includes the maximum value for the AUTO_INCREMENT column, that value is reused in the BDB table, but not in the MyISAM table or the InnoDB table. If you use DELETE FROM tbl_name (without a WHERE clause) in AUTOCOMMIT mode to delete all rows in a table, the sequence is reordered for all table types (except InnoDB and MyISAM).

For MyISAM and BDB tables, you can specify the AUTO_INCREMENT secondary column into a multi-column keyword. In this case, the value removed from the top of the sequence is used again, even for MyISAM tables.

The DELETE statement supports the following modifiers:

· If you specify LOW_PRIORITY, the execution of DELETE is delayed until no other client reads this table.

· For MyISAM tables, if you use the QUICK keyword, the storage engine will not merge the index end nodes during the deletion process, which can speed up some types of deletion operations.

· During the process of deleting rows, the IGNORE keyword causes MySQL to ignore all errors. (Errors encountered during the analysis phase are handled in the normal manner.) Errors that are ignored due to the use of this option are returned as warnings.

In MyISAM tables, deleted records are kept in a linked list, and subsequent INSERT operations will reuse the old record location. To reuse unused space and reduce the file size, use the OPTIMIZE TABLE statement or the myisamchk application to reorganize the table. OPTIMIZE TABLE is simpler, but myisamchk is faster.

QUICK modifier will affect whether the index end nodes are merged during the deletion operation. DELETE QUICK is most useful when the index value for the deleted row is replaced by a similar index value from a later inserted row. In this case, the holes left by the deleted values ​​are reused.

If the index block that is not full spans a certain range of index values, a new insertion will occur. DELETE QUICK has no effect when the deleted value results in an underfilled index block. In this case, using QUICK can result in waste space in unused indexes. The following is an example of this situation:

1. Create a table that contains the indexed AUTO_INCREMENT column.

2. Insert many records into the table. Each insertion produces an index value, which is added to the high end of the index.

3. Use DELETE QUICK to delete a group of records from the low end of the column.

In this case, the index blocks related to the deleted index values ​​become underfilled, but due to the use of QUICK, these index blocks will not be merged with other index blocks. When new values ​​are inserted, these index blocks remain underfilled because the new records do not contain index values ​​within the deleted range. In addition, even if you later use DELETE without including QUICK, these index blocks will still be unfilled, unless some of the deleted index values ​​happen to be in or adjacent to these unfilled blocks. In these cases, if you want to reuse unused index space, use OPTIMIZE TABLE.

If you plan to delete many rows from a table, using DELETE QUICK coupled with OPTIMIZE TABLE can speed things up. Doing so re-indexes rather than doing a large number of index block merge operations.

MySQL’s only LIMIT row_count option for DELETE is used to tell the server the maximum number of rows to be deleted before the control command is returned to the client. This option is used to ensure that a DELETE statement does not take up too much time. You can just repeat the DELETE statement until the number of relevant rows is less than the LIMIT value.

If the DELETE statement includes an ORDER BY clause, the rows are deleted in the order specified in the clause. This clause only works when used in conjunction with LIMIT. For example, the following clause is used to find rows corresponding to the WHERE clause, use timestamp_column for classification, and delete the first (oldest) row:

DELETE FROM somelog
WHERE user = 'jcole'
ORDER BY timestamp_column
LIMIT 1;

You can specify multiple tables in one DELETE statement, based on multiple Deletes rows from a table or multiple tables based on specific conditions in the table. However, you cannot use ORDER BY or LIMIT in a multi-table DELETE statement.

table_references section lists the tables included in the union.

For the first syntax, only delete the corresponding rows in the table listed before the FROM clause. For the second syntax, only the corresponding rows in the table listed in the FROM clause (before the USING clause) are deleted. What this does is, you can delete rows from many tables at the same time and search using the other tables:

DELETE t1, t2 FROM t1, t2, t3 WHERE t1.id=t2.id AND t2.id=t3.id;

or:

DELETE FROM t1, t2 USING t1, t2, t3 WHERE t1.id=t2.id AND t2.id=t3.id;

When searching for rows to be deleted, these statements use all three tables, but only from the table Delete the corresponding rows in t1 and table t2.

The above example shows an inner join using the comma operator, but the multi-table DELETE statement can use all types of joins allowed in the SELECT statement, such as LEFT JOIN.

本语法允许在名称后面加.*,以便与Access相容。

如果您使用的多表DELETE语句包括InnoDB表,并且这些表受外键的限制,则MySQL优化程序会对表进行处理,改变原来的从属关系。在这种情况下,该语句出现错误并返回到前面的步骤。要避免此错误,您应该从单一表中删除,并依靠InnoDB提供的ON DELETE功能,对其它表进行相应的修改。

注释:当引用表名称时,您必须使用别名(如果已给定):

DELETE t1 FROM test AS t1, test2 WHERE ...

进行多表删除时支持跨数据库删除,但是在此情况下,您在引用表时不能使用别名。举例说明:

DELETE test1.tmp1, test2.tmp2 FROM test1.tmp1, test2.tmp2 WHERE ...

目前,您不能从一个表中删除,同时又在子查询中从同一个表中选择。


Statement
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
What are stored procedures in MySQL?What are stored procedures in MySQL?May 01, 2025 am 12:27 AM

Stored procedures are precompiled SQL statements in MySQL for improving performance and simplifying complex operations. 1. Improve performance: After the first compilation, subsequent calls do not need to be recompiled. 2. Improve security: Restrict data table access through permission control. 3. Simplify complex operations: combine multiple SQL statements to simplify application layer logic.

How does query caching work in MySQL?How does query caching work in MySQL?May 01, 2025 am 12:26 AM

The working principle of MySQL query cache is to store the results of SELECT query, and when the same query is executed again, the cached results are directly returned. 1) Query cache improves database reading performance and finds cached results through hash values. 2) Simple configuration, set query_cache_type and query_cache_size in MySQL configuration file. 3) Use the SQL_NO_CACHE keyword to disable the cache of specific queries. 4) In high-frequency update environments, query cache may cause performance bottlenecks and needs to be optimized for use through monitoring and adjustment of parameters.

What are the advantages of using MySQL over other relational databases?What are the advantages of using MySQL over other relational databases?May 01, 2025 am 12:18 AM

The reasons why MySQL is widely used in various projects include: 1. High performance and scalability, supporting multiple storage engines; 2. Easy to use and maintain, simple configuration and rich tools; 3. Rich ecosystem, attracting a large number of community and third-party tool support; 4. Cross-platform support, suitable for multiple operating systems.

How do you handle database upgrades in MySQL?How do you handle database upgrades in MySQL?Apr 30, 2025 am 12:28 AM

The steps for upgrading MySQL database include: 1. Backup the database, 2. Stop the current MySQL service, 3. Install the new version of MySQL, 4. Start the new version of MySQL service, 5. Recover the database. Compatibility issues are required during the upgrade process, and advanced tools such as PerconaToolkit can be used for testing and optimization.

What are the different backup strategies you can use for MySQL?What are the different backup strategies you can use for MySQL?Apr 30, 2025 am 12:28 AM

MySQL backup policies include logical backup, physical backup, incremental backup, replication-based backup, and cloud backup. 1. Logical backup uses mysqldump to export database structure and data, which is suitable for small databases and version migrations. 2. Physical backups are fast and comprehensive by copying data files, but require database consistency. 3. Incremental backup uses binary logging to record changes, which is suitable for large databases. 4. Replication-based backup reduces the impact on the production system by backing up from the server. 5. Cloud backups such as AmazonRDS provide automation solutions, but costs and control need to be considered. When selecting a policy, database size, downtime tolerance, recovery time, and recovery point goals should be considered.

What is MySQL clustering?What is MySQL clustering?Apr 30, 2025 am 12:28 AM

MySQLclusteringenhancesdatabaserobustnessandscalabilitybydistributingdataacrossmultiplenodes.ItusestheNDBenginefordatareplicationandfaulttolerance,ensuringhighavailability.Setupinvolvesconfiguringmanagement,data,andSQLnodes,withcarefulmonitoringandpe

How do you optimize database schema design for performance in MySQL?How do you optimize database schema design for performance in MySQL?Apr 30, 2025 am 12:27 AM

Optimizing database schema design in MySQL can improve performance through the following steps: 1. Index optimization: Create indexes on common query columns, balancing the overhead of query and inserting updates. 2. Table structure optimization: Reduce data redundancy through normalization or anti-normalization and improve access efficiency. 3. Data type selection: Use appropriate data types, such as INT instead of VARCHAR, to reduce storage space. 4. Partitioning and sub-table: For large data volumes, use partitioning and sub-table to disperse data to improve query and maintenance efficiency.

How can you optimize MySQL performance?How can you optimize MySQL performance?Apr 30, 2025 am 12:26 AM

TooptimizeMySQLperformance,followthesesteps:1)Implementproperindexingtospeedupqueries,2)UseEXPLAINtoanalyzeandoptimizequeryperformance,3)Adjustserverconfigurationsettingslikeinnodb_buffer_pool_sizeandmax_connections,4)Usepartitioningforlargetablestoi

See all articles

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

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools