(MariaDB/MySQL) DML (2): data update, delete

Contents of this article:
1.update statement
2.delete statement2.1 single table delete2.2 multiple table delete3.truncate table
 
 

1.update statement

update is used to modify the records in the table.

# 单表更新语法:
UPDATE [LOW_PRIORITY] [IGNORE] table_reference 
  [PARTITION (partition_list)]
  SET col1={expr1|DEFAULT} [,col2={expr2|DEFAULT}] ...
  [WHERE where_condition]
  [ORDER BY ...]
  [LIMIT row_count]

# 多表更新语法:
UPDATE [LOW_PRIORITY] [IGNORE] table_references
    SET col1={expr1|DEFAULT} [, col2={expr2|DEFAULT}] ...
    [WHERE where_condition]

The functions related to each clause and keyword are briefly introduced first, and they will be explained in detail later.

  • low_priority is only valid for storage engines that use table-level locks (such as MyISAM and Aria). It sets the priority of the delete statement lower than the read operation, so that the update will be delayed until no process accesses the table. See: (MariaDB/MySQL) MyISAM storage engine read and write priority .
  • ignore is to ignore the error when updating a row and continue to update other rows.
  • The where clause filters out the rows to update. If no where clause is given, update updates all rows in the entire table.
  • The order by clause indicates that the filtered data is sorted first, and then the rows are updated in order after sorting. When updating certain rows, using order by can solve some errors.
  • The limit clause means to update a certain number of rows.

E.g:

# 单表更新
UPDATE table_name SET column1 = value1, column2 = value2 WHERE id=100;

Updates the specified number of rows sorted.

update book set bookcount=2 where bookname in ('ss') order by bookid limit 10;

Multi-table update. Note that the following statement will update the data in both tables .

UPDATE BOOK,BOOK2 SET BOOK.bookcount=2 ,BOOK2.bookcount=3 WHERE BOOK.bookid=1 AND BOOK2.bookid=1;

Update a table's data based on other tables. Note that the following statement only updates data in one table .

update t,t1 set t1.name='newname' where t1.id=t2.id;
update t set name='newname' where t.id=(select max(id) from t1);

Note that SQL Server supports the following update from syntax, but MySQL/MariaDB does not.

-- 使用多表联接为软件测试低于65分的学生减5分
UPDATE TScore SET mark = mark - 5 
FROM TScore a JOIN TSubject b ON a.subJectID = b.subJectID
WHERE b.subJectName = '软件测试' AND mark < 65

Here are a few special cases to be aware of about updates.

(1). When the key value is repeated during the update, you can consider using the order by clause.

For example, in the following table: id is the primary key, and duplicates are not allowed.

create or replace table t(id int primary key,sex char(3),name char(20));
insert into t values(1,'nan','longshuai1'),
                      (2,'nan','longshuai2'),
                      (3,'nv','xiaofang1'),
                      (4,'nv','xiaofang2'),
                      (5,'nv','xiaofang3'),
                      (6,'nv','xiaofang4'),
                      (7,'nv','tun\'er'),
                      (8,'nan','longshuai3');

The following statement will fail the update because the primary key id will be duplicated if the update is successful.

update t set id=id+1 where id>5;
ERROR 1062 (23000): Duplicate entry '7' for key 'PRIMARY'

But after using order by, it will be able to update normally, because it will sort first, and then update the result set in descending order.

update t set id=id+1 where id>5 order by id desc;
select * from t where id>5;
+----+------+------------+
| id | sex  | name       |
+----+------+------------+
|  7 | nv   | xiaofang4  |
|  8 | nv   | tun'er     |
|  9 | nan  | longshuai3 |
+----+------+------------+

(2). Be sure to pay attention to the simultaneity of the set assignment statement in update.

Multiple assignment statements are evaluated from left to right, unless sql_modea SIMULTANEOUS_ASSIGNMENTmode is specified (which is supported since MariaDB 10.3.5), in which case the UPDATE statement evaluates all assignment statements simultaneously. (Note: The update assignment statement of standard SQL is synchronous)

For example, given the following table:

CREATE OR REPLACE TABLE tx (c1 INT, c2 INT);
INSERT INTO tx VALUES (10,10);

The following update can be executed correctly, and the value of the c2 field after the update is the same as the value of c1.

UPDATE tx SET c1=c1+1,c2=c1;
SELECT * FROM tx;
+------+------+
| c1   | c2   |
+------+------+
|   11 |   11 |
+------+------+

Set the sql_mode mode SIMULTANEOUS_ASSIGNMENT, and then execute the same update statement.

/* 由于同时评估各赋值语句,所以更新后c1的值会加1,c2的值等于更新前的c1 */
SET @@sql_mode=CONCAT(@@sql_mode,',SIMULTANEOUS_ASSIGNMENT');
UPDATE tx SET c1=c1+1,c2=c1;
SELECT * FROM tx;
+------+------+
| c1   | c2   |
+------+------+
|   12 |   11 |
+------+------+

(3). Update the same data as source and target.

Prior to MariaDB 10.3.2, executing the update statement below would fail.

update t set id='10' where id=(select max(t.id) from t);  
ERROR 1093 (HY000): Table 't' is specified twice, both as a target for 'UPDATE' and as a separate source for data

But since MariaDB 10.3.2, it is allowed to execute such update statement.

2.delete statement

delete is used to delete records in the table. You can delete single-table data or multiple-table data.

Look at the syntax first:

# 单表删除语法
DELETE [LOW_PRIORITY] [QUICK] [IGNORE] 
    FROM tbl_name [PARTITION (partition_list)]
    [WHERE where_condition]
    [ORDER BY ...]
    [LIMIT row_count]
    [RETURNING select_expr 
      [, select_expr ...]]

# 多表语法:
DELETE [LOW_PRIORITY] [QUICK] [IGNORE]
    tbl_name[.*] [, tbl_name[.*]] ...
    FROM table_references
    [WHERE where_condition]
# 或:
DELETE [LOW_PRIORITY] [QUICK] [IGNORE]
    FROM tbl_name[.*] [, tbl_name[.*]] ...
    USING table_references
    [WHERE where_condition]

The functions related to each clause and keyword are briefly introduced first, and they will be explained in detail later.

  • The from clause specifies the data in which table to delete. If it is a multi-table syntax, it may only provide the reference function, but not necessarily delete the data in it.
  • low_priority is only valid for storage engines that use table-level locks (such as MyISAM and Aria). It sets the priority of the delete statement lower than the read operation, so that delete will be delayed until no process accesses the table. See: (MariaDB/MySQL) MyISAM storage engine read and write priority .
  • quick is to notify the storage engine to combine the delete operations. After the storage engine receives this notification, the operations to delete multiple rows will be combined into a batch. When the size of the batch reaches a certain level, it will be deleted at one time, which can improve the deletion of data to a certain extent. s efficiency. May not work for InnoDB/XtraDB, but works for MyISAM and Aria.
  • ignore is to ignore the error when deleting a line and continue to delete other lines.
  • The where clause filters out the rows to delete. If no where clause is given, delete deletes all rows in the entire table.
  • The order by clause means to sort the filtered data first, and delete the rows in order after sorting.
  • The limit clause means to delete a certain number of rows.
  • The returning clause is used to return data related to the deleted row. This is a very user-friendly function of MariaDB, which not only allows us to know which rows have been deleted, but also sometimes restores accidentally deleted rows. MySQL does not support this feature.
  • The using clause is used in multi-table delete syntax.

The from clause must be used in the delete statement in MySQL/MariaDB. When deleting a single table, the table name must be placed in the from clause, while in the multi-table delete syntax, multiple tables can be placed before the from clause. People who are used to SQL Server may not be used to it at first. For convenience reasons, delete in SQL Server often does not write the from clause.

2.1 Single table deletion

Given the following table, and insert some data.

create or replace table t(id int primary key,sex char(3),name char(20));
insert into t values(1,'nan','longshuai1'),
                      (2,'nan','longshuai2'),
                      (3,'nv','xiaofang1'),
                      (4,'nv','xiaofang2'),
                      (5,'nv','xiaofang3'),
                      (6,'nv','xiaofang4'),
                      (7,'nv','tun\'er'),
                      (8,'nan','longshuai3');

Delete records with sex='nv' and id>6.

delete from t where id>6 and sex='nv';

For the delete statement, the order by clause is mainly used in conjunction with the limit clause.

delete from t order by id limit 2;

If you use the returning clause, you can customize what data is returned when a row is deleted. Note that the following statement will fail prior to MariaDB 10.3.1. as follows.

delete from t where id=(select max(id) from t) returning concat("delete id: ",id) as maxid;
+--------------+
| maxid        |
+--------------+
| delete id: 8 |
+--------------+

Or return the values ​​of all fields of the deleted row:

delete from t returning *;
+----+------+-----------+
| id | sex  | name      |
+----+------+-----------+
|  3 | nv   | xiaofang1 |
|  4 | nv   | xiaofang2 |
|  5 | nv   | xiaofang3 |
|  6 | nv   | xiaofang4 |
+----+------+-----------+

Note that in the following delete statement, the same source and same target data is deleted. Before MariaDB 10.3.1, the delete statement could not delete such records. The error message is as follows:

delete from t where id=(select max(id) from t);
ERROR 1093 (HY000): Table 't' is specified twice, both as a target for 'DELETE' and as a separate source for data

But since MariaDB 10.3.1, it is allowed to delete such records.

2.2 Multi-table deletion

There are two syntaxes, one is to put the table reference before the from clause, the other is to use the using clause. They are actually equivalent.

If you don't understand the syntax below, please consider delete tbl_namereplacing this part with select column_list. The execution process of delete is the same as that of select, except that after filtering the data, one is to further select the filtered result set, and the other is the result set filtered by delete.

The following statement will delete the records with the same id in the two tables t and t1. Note that the contents of both tables are deleted.

delete t,t1 from t join t1 on t.id=t1.id;
# 等价于
delete from t,t1 using t join t1 on t.id=t1.id;

If you just want to delete the contents of one table, but need to refer to multiple tables, you can refer to the following statement. This statement will only delete the contents of the t table, not the contents of the t1 table.

# delete tbl_name1 from tbl_name1 join tbl_name2 ....
delete t from t join t1 on t.id=t1.id;

For example, delete records that are in table t but not in table t1.

delete t from t left join t1 on t.id=t1.id where t1.id is NULL;

If an alias is used, then like select, when the delete list refers to the table name, the alias needs to be used.

# 正确的语法
DELETE a1, a2 FROM t1 AS a1 INNER JOIN t2 AS a2 WHERE a1.id=a2.id;
DELETE FROM a1, a2 USING t1 AS a1 INNER JOIN t2 AS a2 WHERE a1.id=a2.id;

# 错误的语法
DELETE t1 AS a1, t2 AS a2 FROM t1 INNER JOIN t2 WHERE a1.id=a2.id;
DELETE FROM t1 AS a1, t2 AS a2 USING t1 INNER JOIN t2 WHERE a1.id=a2.id;

3.truncate table

truncate tableUsed to clear a table. truncate tableIt is equivalent to drop table + re-create tabletwo operations, so it is a DDL statement rather than a DML statement, and therefore it requires the drop permission of the table, and the speed is much faster than that of the delete table, especially when the table is relatively large.

When re-creating a table, it rebuilds the table according to the table structure in the ".frm" file, so attributes such as indexes are preserved. But the most recent value of auto_increment will be reset, because the table is deleted, its auto_increment value is all cleared.

It truncate tablewill .

It truncate tablewill .

If there are triggers on the table, no triggers truncate tablewill fire. Because MariaDB/MySQL does not support DDL triggers.

 

Back to the outline of the Linux series of articles: http://www.cnblogs.com/f-ck-need-u/p/7048359.html Back to the outline of the website architecture series of articles: http://www.cnblogs.com/f- ck-need-u/p/7576137.html Back to database series article outline: http://www.cnblogs.com/f-ck-need-u/p/7586194.html Reprint please indicate the source: http:/ /www.cnblogs.com/f-ck-need-u/p/8912026.html



Note: If you think this article is not bad, please click on the recommendation in the lower right corner. Your support can stimulate the author's greater enthusiasm for writing, thank you very much!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324657915&siteId=291194637