[Reprint] SQL update select combined statement detailed explanation and application

The most common update syntax is:

1
2
UPDATE TABLE_NAME
SET column_name1 = VALUE WHRER column_name2 = VALUE

If my update value Value is taken from a select statement, and there are many columns, it is very troublesome to use this syntax

First, to select them and put them on temporary variables, many of which are difficult to save. Second, assign the variable again.

It is very troublesome to have more columns. Can you insert the result of the entire Select statement like Insert? As in the following::

1
2
3
INSERT INTO table1
(c1, c2, c3)
(SELECT v1, v2, v3 FROM table2)

The answer is yes, the specific syntax is as follows:

1
2
3
4
5
6
UPDATE table1 alias
SET (column_name,column_name ) = (
SELECT (column_name, column_name)
FROM table2
WHERE column_name = alias.column_name)
WHERE column_name = VALUE

The following is such an example: Two tables a and b, want to make the memo field value in b equal to the name value table a of the corresponding id in table a:

1
2
3
4
id    name
1 king
2 Lee
3 sheets

Table b:

1
2
3
4
id    ClientName   
1
2
3

(MS SQL Server) Statement:

1
UPDATE b   SET   ClientName    = a.name    FROM a,b    WHERE a.id = b.id

(Oralce) statement:

1
UPDATE b   SET   (ClientName)    =   (SELECT name FROM a WHERE b.id = a.id)

Update set from statement format When both where and set need to be associated with a table for query, when the entire update is executed, the associated table needs to be scanned twice, which is obviously inefficient.

For this situation, the solution for Sybase and SQL SERVER is to use the UPDATE...SET...FROM...WHERE... syntax, which is actually to get the updated data from the source table.

In SQL, table joins (left join, right join, inner join, etc.) are often used in select statements. In fact, in SQL syntax, these joins can also be used for update and delete statements, and the use of joins in these statements often results in a multiplier effect.

1
2
UPDATE T_OrderForm SET T_OrderForm.SellerID =B.L_TUserID
FROM T_OrderForm A LEFT JOIN T_ProductInfo   B ON B.L_ID=A.ProductID

Used to synchronize the data of the two tables!

Syntax supported by both Oracle and DB2:

1
UPDATE A SET (A1, A2, A3) = (SELECT B1, B2, B3 FROM B WHERE A.ID = B.ID)

MS SQL Server does not support such a syntax, the corresponding writing is:

1
UPDATE A  SET A1 = B1, A2 = B2, A3 = B3  FROM A LEFT JOIN B ON A.ID = B.ID

Personally feel that the Update syntax of MS SQL Server is more powerful. MS SQL SERVER writing:

1
UPDATE A SET A1 = B1, A2 = B2, A3 = B3 FROM A, B WHERE A.ID = B.ID

The writing method in Oracle and DB2 is more troublesome, as follows:

1
2
UPDATE A SET (A1, A2, A3) = (SELECT B1, B2, B3 FROM B WHERE A.ID = B.ID)
WHERE ID IN (SELECT B.ID FROM B WHERE A.ID = B.ID)

Guess you like

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