mysql _update join

Upload: bluebird1969

Post on 05-Oct-2015

236 views

Category:

Documents


0 download

DESCRIPTION

MySQL _update Join

TRANSCRIPT

  • 1/29/2015 MySQL :: MySQL 5.0 Reference Manual :: 13.2.10 UPDATE Syntax

    http://dev.mysql.com/doc/refman/5.0/en/update.html 1/19

    13.2.9.11 Rewriting Subqueries as Joins

    13.3 MySQL Transactional and LockingStatements

    Section Navigation [Toggle]

    13.2 Data ManipulationStatements

    13.2.1 CALL Syntax

    13.2.2 DELETE Syntax

    13.2.3 DO Syntax

    13.2.4 HANDLER Syntax

    13.2.5 INSERT Syntax

    13.2.6 LOAD DATA INFILESyntax

    13.2.7 REPLACE Syntax

    13.2.8 SELECT Syntax

    13.2.9 Subquery Syntax

    13.2.10 UPDATE Syntax

    MySQL 5.0 Reference Manual :: 13 SQL Statement Syntax :: 13.2 Data Manipulation Statements ::13.2.10 UPDATE Syntax

    13.2.10 UPDATE Syntax

    Single-table syntax:

    UPDATE [LOW_PRIORITY] [IGNORE] table_reference

    SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...

    [WHERE where_condition]

    [ORDER BY ...]

    [LIMIT row_count]

    Multiple-table syntax:

    UPDATE [LOW_PRIORITY] [IGNORE] table_references

    SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...

    [WHERE where_condition]

    For the single-table syntax, the UPDATE statement updatescolumns of existing rows in the named table with new values.The SET clause indicates which columns to modify and thevalues they should be given. Each value can be given as an expression, or the keyword DEFAULT to seta column explicitly to its default value. The WHERE clause, if given, specifies the conditions that identifywhich rows to update. With no WHERE clause, all rows are updated. If the ORDER BY clause is specified,the rows are updated in the order that is specified. The LIMIT clause places a limit on the number ofrows that can be updated.

    For the multiple-table syntax, UPDATE updates rows in each table named in table_references thatsatisfy the conditions. Each matching row is updated once, even if it matches the conditions multipletimes. For multiple-table syntax, ORDER BY and LIMIT cannot be used.

    where_condition is an expression that evaluates to true for each row to be updated. For expressionsyntax, see Section 9.5, Expression Syntax.

    table_references and where_condition are is specified as described in Section 13.2.8, SELECTSyntax.

    You need the UPDATE privilege only for columns referenced in an UPDATE that are actually updated.You need only the SELECT privilege for any columns that are read but not modified.

    The UPDATE statement supports the following modifiers:

    With the LOW_PRIORITY keyword, execution of the UPDATE is delayed until no other clients arereading from the table. This affects only storage engines that use only table-level locking (suchas MyISAM, MEMORY, and MERGE).

    With the IGNORE keyword, the update statement does not abort even if errors occur during theupdate. Rows for which duplicate-key conflicts occur on a unique key value are not updated.Rows updated to values that would cause data conversion errors are updated to the closest validvalues instead.

    If you access a column from the table to be updated in an expression, UPDATE uses the current value ofthe column. For example, the following statement sets col1 to one more than its current value:

    UPDATE t1 SET col1 = col1 + 1;

    http://dev.mysql.com/doc/refman/5.0/en/rewriting-subqueries.htmlhttp://dev.mysql.com/doc/refman/5.0/en/sql-syntax-transactions.htmlhttp://dev.mysql.com/doc/refman/5.0/en/sql-syntax-data-manipulation.htmlhttp://dev.mysql.com/doc/refman/5.0/en/call.htmlhttp://dev.mysql.com/doc/refman/5.0/en/delete.htmlhttp://dev.mysql.com/doc/refman/5.0/en/do.htmlhttp://dev.mysql.com/doc/refman/5.0/en/handler.htmlhttp://dev.mysql.com/doc/refman/5.0/en/insert.htmlhttp://dev.mysql.com/doc/refman/5.0/en/load-data.htmlhttp://dev.mysql.com/doc/refman/5.0/en/replace.htmlhttp://dev.mysql.com/doc/refman/5.0/en/select.htmlhttp://dev.mysql.com/doc/refman/5.0/en/subqueries.htmlhttp://dev.mysql.com/doc/refman/5.0/en/index.htmlhttp://dev.mysql.com/doc/refman/5.0/en/sql-syntax.htmlhttp://dev.mysql.com/doc/refman/5.0/en/sql-syntax-data-manipulation.htmlhttp://dev.mysql.com/doc/refman/5.0/en/update.htmlhttp://dev.mysql.com/doc/refman/5.0/en/update.htmlhttp://dev.mysql.com/doc/refman/5.0/en/expressions.htmlhttp://dev.mysql.com/doc/refman/5.0/en/select.htmlhttp://dev.mysql.com/doc/refman/5.0/en/privileges-provided.html#priv_updatehttp://dev.mysql.com/doc/refman/5.0/en/update.htmlhttp://dev.mysql.com/doc/refman/5.0/en/privileges-provided.html#priv_selecthttp://dev.mysql.com/doc/refman/5.0/en/update.htmlhttp://dev.mysql.com/doc/refman/5.0/en/update.htmlhttp://dev.mysql.com/doc/refman/5.0/en/update.html

  • 1/29/2015 MySQL :: MySQL 5.0 Reference Manual :: 13.2.10 UPDATE Syntax

    http://dev.mysql.com/doc/refman/5.0/en/update.html 2/19

    The second assignment in the following statement sets col2 to the current (updated) col1 value, notthe original col1 value. The result is that col1 and col2 have the same value. This behavior differsfrom standard SQL.

    UPDATE t1 SET col1 = col1 + 1, col2 = col1;

    Single-table UPDATE assignments are generally evaluated from left to right. For multiple-table updates,there is no guarantee that assignments are carried out in any particular order.

    If you set a column to the value it currently has, MySQL notices this and does not update it.

    If you update a column that has been declared NOT NULL by setting to NULL, an error occurs if strictSQL mode is enabled; otherwise, the column is set to the implicit default value for the column data typeand the warning count is incremented. The implicit default value is 0 for numeric types, the empty string('') for string types, and the zero value for date and time types. See Section 11.6, Data Type DefaultValues.

    UPDATE returns the number of rows that were actually changed. The mysql_info() C API functionreturns the number of rows that were matched and updated and the number of warnings that occurredduring the UPDATE.

    You can use LIMIT row_count to restrict the scope of the UPDATE. A LIMIT clause is a rows-matchedrestriction. The statement stops as soon as it has found row_count rows that satisfy the WHERE clause,whether or not they actually were changed.

    If an UPDATE statement includes an ORDER BY clause, the rows are updated in the order specified bythe clause. This can be useful in certain situations that might otherwise result in an error. Suppose thata table t contains a column id that has a unique index. The following statement could fail with aduplicate-key error, depending on the order in which rows are updated:

    UPDATE t SET id = id + 1;

    For example, if the table contains 1 and 2 in the id column and 1 is updated to 2 before 2 is updated to3, an error occurs. To avoid this problem, add an ORDER BY clause to cause the rows with larger idvalues to be updated before those with smaller values:

    UPDATE t SET id = id + 1 ORDER BY id DESC;

    You can also perform UPDATE operations covering multiple tables. However, you cannot use ORDER BYor LIMIT with a multiple-table UPDATE. The table_references clause lists the tables involved in thejoin. Its syntax is described in Section 13.2.8.2, JOIN Syntax. Here is an example:

    UPDATE items,month SET items.price=month.price

    WHERE items.id=month.id;

    The preceding example shows an inner join that uses the comma operator, but multiple-table UPDATEstatements can use any type of join permitted in SELECT statements, such as LEFT JOIN.

    If you use a multiple-table UPDATE statement involving InnoDB tables for which there are foreign keyconstraints, the MySQL optimizer might process tables in an order that differs from that of theirparent/child relationship. In this case, the statement fails and rolls back. Instead, update a single tableand rely on the ON UPDATE capabilities that InnoDB provides to cause the other tables to be modifiedaccordingly. See Section 14.2.3.4, InnoDB and FOREIGN KEY Constraints.

    Currently, you cannot update a table and select from the same table in a subquery.

    Index hints (see Section 13.2.8.3, Index Hint Syntax) are accepted but ignored for UPDATE statements.

    http://dev.mysql.com/doc/refman/5.0/en/update.htmlhttp://dev.mysql.com/doc/refman/5.0/en/data-type-defaults.htmlhttp://dev.mysql.com/doc/refman/5.0/en/update.htmlhttp://dev.mysql.com/doc/refman/5.0/en/mysql-info.htmlhttp://dev.mysql.com/doc/refman/5.0/en/update.htmlhttp://dev.mysql.com/doc/refman/5.0/en/update.htmlhttp://dev.mysql.com/doc/refman/5.0/en/update.htmlhttp://dev.mysql.com/doc/refman/5.0/en/update.htmlhttp://dev.mysql.com/doc/refman/5.0/en/update.htmlhttp://dev.mysql.com/doc/refman/5.0/en/join.htmlhttp://dev.mysql.com/doc/refman/5.0/en/update.htmlhttp://dev.mysql.com/doc/refman/5.0/en/select.htmlhttp://dev.mysql.com/doc/refman/5.0/en/update.htmlhttp://dev.mysql.com/doc/refman/5.0/en/innodb-foreign-key-constraints.htmlhttp://dev.mysql.com/doc/refman/5.0/en/index-hints.htmlhttp://dev.mysql.com/doc/refman/5.0/en/update.html

  • 1/29/2015 MySQL :: MySQL 5.0 Reference Manual :: 13.2.10 UPDATE Syntax

    http://dev.mysql.com/doc/refman/5.0/en/update.html 3/19

    Previous / Next / Up / Table of Contents

    User Comments

    Posted by Vjero Fiala on December 6 2003 1:21am [Delete] [Edit]

    Update one field with more fields from another table

    Table A

    +--------+-----------+| A-num | text | | 1 | || 2 | || 3 | || 4 | || 5 | |+--------+-----------+

    Table B:

    +------+------+--------------+| B-num| date | A-num | | 22 | 01.08.2003 | 2 || 23 | 02.08.2003 | 2 | | 24 | 03.08.2003 | 1 || 25 | 04.08.2003 | 4 || 26 | 05.03.2003 | 4 |

    I will update field text in table Awith UPDATE `Table A`,`Table B`SET `Table A`.`text`=concat_ws('',`Table A`.`text`,`Table B`.`B-num`," from ",`Table B`.`date`,'/')WHERE `Table A`.`A-num` = `Table B`.`A-num`

    and come to this resultTable A

    +--------+------------------------+| A-num | text | | 1 | 24 from 03 08 2003 / || 2 | 22 from 01 08 2003 / | | 3 | || 4 | 25 from 04 08 2003 / || 5 | |

    --------+-------------------------+(only one field from Table B is accepted)

    But i will come to this result Table A

    +--------+--------------------------------------------+| A-num | text | | 1 | 24 from 03 08 2003 || 2 | 22 from 01 08 2003 / 23 from 02 08 2003 / |

    http://dev.mysql.com/doc/refman/5.0/en/rewriting-subqueries.htmlhttp://dev.mysql.com/doc/refman/5.0/en/sql-syntax-transactions.htmlhttp://dev.mysql.com/doc/refman/5.0/en/sql-syntax-data-manipulation.htmlhttp://dev.mysql.com/doc/refman/5.0/en/index.htmlhttp://dev.mysql.com/doc/mysql/comment.php?id=3689&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html&action=deletehttp://dev.mysql.com/doc/mysql/comment.php?id=3689&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html

  • 1/29/2015 MySQL :: MySQL 5.0 Reference Manual :: 13.2.10 UPDATE Syntax

    http://dev.mysql.com/doc/refman/5.0/en/update.html 4/19

    | 3 | || 4 | 25 from 04 08 2003 / 26 from 05 03 2003 / || 5 | |+--------+--------------------------------------------+

    Posted by Babu Ramesh on January 12 2004 11:33pm [Delete] [Edit]

    Update column in a table whose values are not found in another table.

    UPDATE TABLE_1 LEFT JOIN TABLE_2 ON TABLE_1.COLUMN_1= TABLE_2.COLUMN_2 SET TABLE_1.COLUMN = EXPR WHERE TABLE_2.COLUMN2 IS NULL

    An outerjoin is performed based on the equijoin condition. Records not matching the equijoin from table2 are marked with null.

    This facilitates to update table1 column with expression whose corresponding value from table2 isreturned as NULL

    Posted by Adam Boyle on March 2 2004 2:28pm [Delete] [Edit]

    It took me a few minutes to figure this out, but the syntax for UPDATING ONE TABLE ONLY using arelationship between two tables in MySQL 4.0 is actually quite simple:

    update t1, t2 set t1.field = t2.value where t1.this = t2.that;

    Posted by Neil Yalowitz on March 30 2004 7:56am [Delete] [Edit]

    It should be noted that even simple applications of UPDATE can conflict with the 'safe mode' setting ofthe mysql daemon. Many server admins default the MySQL daemon to 'safe mode'.

    If UPDATE gives an error like this:

    "You are using safe update mode and you tried to update a table without...etc."

    ...then it may be that your .cnf file must be edited to disable safemode. This worked for me. In order forthe change in the .cnf file to take effect, you must have permission to restart mysqld in the server OSenvironment. There is a page in the online documentation that explains safe mode entitled 'safe ServerStartup Script'.

    Posted by Csaba Gabor on May 26 2004 8:25am [Delete] [Edit]

    Suppose you have a table where each row is associated with a certain group (For example, orders areassociated with the customers placing them) where each item WITHIN the group has a distinct number(For example, each person my have a sequence of competition results - each person, therefore, has a1st, 2nd, 3rd... competition).If you would like to renumber items within their group so that each has the same baseline (say 0), hereis an example way to proceed:

    Create TEMPORARY Table Groups (Id INTEGER AUTO_INCREMENT PRIMARY KEY,Name VARCHAR(31), GroupId VARCHAR(31), ValWithinGroup INTEGER);INSERT INTO Groups VALUES (null, "Davy", "Boy", 2);INSERT INTO Groups VALUES (null, "Mary", "Girl", 2);INSERT INTO Groups VALUES (null, "Bill", "Boy", 5);INSERT INTO Groups VALUES (null, "Jill", "Girl", -3);INSERT INTO Groups VALUES (null, "Fred", "Boy", 3);

    # Find the lowest value for each group

    http://dev.mysql.com/doc/mysql/comment.php?id=3847&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html&action=deletehttp://dev.mysql.com/doc/mysql/comment.php?id=3847&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.htmlhttp://dev.mysql.com/doc/mysql/comment.php?id=4103&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html&action=deletehttp://dev.mysql.com/doc/mysql/comment.php?id=4103&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.htmlhttp://dev.mysql.com/doc/mysql/comment.php?id=4241&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html&action=deletehttp://dev.mysql.com/doc/mysql/comment.php?id=4241&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.htmlhttp://dev.mysql.com/doc/mysql/comment.php?id=4474&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html&action=deletehttp://dev.mysql.com/doc/mysql/comment.php?id=4474&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html

  • 1/29/2015 MySQL :: MySQL 5.0 Reference Manual :: 13.2.10 UPDATE Syntax

    http://dev.mysql.com/doc/refman/5.0/en/update.html 5/19

    CREATE TEMPORARY TABLE GroupSum AS SELECT GroupId, MIN(ValWithinGroup)AS baseVal FROM Groups GROUP BY GroupId;# create an index so mySQL can efficiently matchALTER TABLE GroupSum ADD UNIQUE (GroupId);# finally, make the baseline adjustmentUPDATE Groups LEFT JOIN GroupSum USING (GroupId)SET ValWithinGroup=ValWithinGroup-baseVal;SELECT * FROM Groups;# 1 Davy Boy 0# 2 Mary Girl 5# 3 Bill Boy 3# 4 Jill Girl 0# 5 Fred Boy 1#Each group ("Boy", "Girl") now has a (lowest) ValWithinGroup entry of 0.

    Notes: That index addition is necessary because on larger tables mySQL would rather die than figure to(internally) index a single column join.

    I was not able, using mySQL 4.1.1, to do this as a subquery:UPDATE Groups LEFT JOIN (SELECT GroupId, MIN(ValWithinGroup) AS baseVal FROM GroupsGROUP BY GroupId) AS GrpSum USING (GroupId) SET ValWithinGroup=ValWithinGroup-baseVal;

    Csaba Gabor

    Posted by Micha ukaszewski on June 10 2004 9:23pm [Delete] [Edit]

    UPDATE Syntax with "on-line" updating value limitations.

    I had a problem - a had to update a column "rate" but if the existince or new value is greater then 5 this"5" will be finally value in field.So, I do it in one "magick" query ;)Here an example:

    "3" is a some value, from form or something

    update item set rate = case when round((rate+3)/2) < 6 then round((rate+3)/2) else 5 end where id = 1 and rate

  • 1/29/2015 MySQL :: MySQL 5.0 Reference Manual :: 13.2.10 UPDATE Syntax

    http://dev.mysql.com/doc/refman/5.0/en/update.html 6/19

    could return a different value than is updated) then you can use a mysql variable like this:

    update some_tableset col = col + 1where key = 'some_key_value'and @value := col

    The @value := col will always evaluate to true and will store the col value before the update in the@value variable.

    You could then do

    select @value;

    in order to see what the value was before you updated it

    Posted by Vladimir Petrov on December 9 2004 1:44pm [Delete] [Edit]

    MySQL uses Watcom (Oracle) syntax for UPDATE, so it's possible to write something like:

    update Table1 t1 join Table2 t2 on t1.ID=t2.t1IDjoin Table3 t3 on t2.ID=t3.t2IDset t1.Value=12345where t3.ID=54321

    Posted by Matt Ryan on February 16 2005 8:20pm [Delete] [Edit]

    Here's a workaround for the update/subquery/cant do self table "bug"

    Senario is, ID 8 has multiple records, only the last (highest) record needs to be changed

    update t1 set c1 = 'NO'where id='8'order by recno desc limit 1

    I would prefer update t1 set c1='NO' WHERE ID=8 AND RECNO = (SELECT MAX(RECNO) FROM T1WHERE ID=8)

    But that's not currently allowed

    Posted by Bob Terrell on February 24 2005 4:34am [Delete] [Edit]

    If you want to update a table based on an aggregate function applied to another table, you can use acorrelated subquery, for example:

    UPDATE table1 SET table1field = (SELECT MAX(table2.table2field) FROM table2 WHEREtable1.table1field = table2.table2field)

    This can be helpful if you need to create a temporary table storing an ID (for, say, a person) and a "lastdate" and already have another table storing all dates (for example, all dates of that person's orders).

    Additional information on MySQL correlated subqueries is athttp://dev.mysql.com/doc/mysql/en/correlated-subqueries.html

    Posted by Ken Miller on April 6 2005 6:34am [Delete] [Edit]

    I was looking at this example:

    update itemset rate = case when round((rate+3)/2) < 6 then round((rate+3)/2) else 5 end

    http://dev.mysql.com/doc/mysql/comment.php?id=5402&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html&action=deletehttp://dev.mysql.com/doc/mysql/comment.php?id=5402&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.htmlhttp://dev.mysql.com/doc/mysql/comment.php?id=5740&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html&action=deletehttp://dev.mysql.com/doc/mysql/comment.php?id=5740&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.htmlhttp://dev.mysql.com/doc/mysql/comment.php?id=5778&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html&action=deletehttp://dev.mysql.com/doc/mysql/comment.php?id=5778&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.htmlhttp://dev.mysql.com/doc/mysql/en/correlated-subqueries.htmlhttp://dev.mysql.com/doc/mysql/comment.php?id=5949&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html&action=deletehttp://dev.mysql.com/doc/mysql/comment.php?id=5949&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html

  • 1/29/2015 MySQL :: MySQL 5.0 Reference Manual :: 13.2.10 UPDATE Syntax

    http://dev.mysql.com/doc/refman/5.0/en/update.html 7/19

    where id = 1 and rate

  • 1/29/2015 MySQL :: MySQL 5.0 Reference Manual :: 13.2.10 UPDATE Syntax

    http://dev.mysql.com/doc/refman/5.0/en/update.html 8/19

    5 | 2 | D | 2 6 | 2 | A | 3 7 | 2 | E | 4 8 | 2 | F | 5 9 | 2 | G | 610 | 2 | H | 7

    Moving D,E,F,G To route 1 SET @pos=(SELECT max(t1.pos) FROM busstops t1 WHERE t1.route = 1 );UPDATE busstops SET pos = ( SELECT @pos := @pos +1 ), route =1 WHERE id IN (5,7,8,9)

    I doubt this could be done otherwise since referencing the table you wish to update within the subquerycreates circular references

    After DELETE or UPDATE i.e. when a row of a subset is lost/deleted/moved away from it, the wholesubset will need to be reordered. This can be done similarily :

    SET @pos=0;UPDATE busstops SET pos = ( SELECT @pos := @pos +1 ) WHERE route = 1 ORDER BY pos ASC

    Chris H (chansel0049)

    Posted by Anders Elton on November 24 2005 10:03pm [Delete] [Edit]

    I experienced a weird issue converting from 4 to 5.

    A is a normal table, B is a temporary table:Worked in 4update A, B set A.population=B.pop_count where A.id=B.id

    In version 5, however, the above query only updated one element while still matching "all"

    In 5 I had to do it like this:update A RIGHT JOIN B on A.id=B.id set A.population=B.pop_countUpdates all population counts correctly.

    [edit: RIGHT JOIN not LEFT JOIN...]

    Posted by Jan Slauer on December 9 2005 1:37pm [Delete] [Edit]

    I had the same problem after update from mysql 4.x.x to 5.x.x. I just exported all the tables to files viaPhpMyAdminand imported them back. Now everything works fine.

    Posted by [name withheld] on March 17 2006 1:09pm [Delete] [Edit]

    Related to the post of Mohamed Hossam on May 9 2005 4:38amA more general method to updtate more one row:

    UPDATE table SET f1='foo', f2= IF(f3=value,one,IF(f3=value_bis,two,f2)) WHERE f5='afected'

    This set the values of field 'f2' according to the values of field 'f3' in the rows field f5 'afected'.

    Posted by Rafi B. on April 26 2006 6:44pm [Delete] [Edit]

    Here is a way to use multiple tables in your UPDATE statement, but actually copying one row values intothe other, meaning, we're using the same table:

    http://dev.mysql.com/doc/mysql/comment.php?id=6908&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html&action=deletehttp://dev.mysql.com/doc/mysql/comment.php?id=6908&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.htmlhttp://dev.mysql.com/doc/mysql/comment.php?id=6969&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html&action=deletehttp://dev.mysql.com/doc/mysql/comment.php?id=6969&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.htmlhttp://dev.mysql.com/doc/mysql/comment.php?id=7358&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html&action=deletehttp://dev.mysql.com/doc/mysql/comment.php?id=7358&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.htmlhttp://dev.mysql.com/doc/mysql/comment.php?id=7527&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html&action=deletehttp://dev.mysql.com/doc/mysql/comment.php?id=7527&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html

  • 1/29/2015 MySQL :: MySQL 5.0 Reference Manual :: 13.2.10 UPDATE Syntax

    http://dev.mysql.com/doc/refman/5.0/en/update.html 9/19

    UPDATE jobs AS toTable, jobs AS fromTableSETtoTable.job_type_id = fromTable.job_type_id,toTable.job_company_id = fromTable.job_company_id,toTable.job_source = fromTable.job_source,WHERE(toTable.job_id = 6)AND(fromTable.job_id = 1)

    --------------Pretty cool. What I'm doing here is copying the information I need from the row where job_id=1 to therow where job_id=6, on the same table.

    Posted by Christopher Marshall on June 7 2006 3:25pm [Delete] [Edit]

    Adam Boyle's commment above was just what I was trying to do, update one table based on arelationship between that table and another. His example was:

    update t1,t2 set t1.field=t2.value where t1.this=t2.that;

    That strikes me as an elegant syntax. Here is the closest I could come up with for doing that on Oracle:

    update t1 set t1.field=(select value from t2 where t1.this=t2.that) where t1.this in (select that from t2);

    That strikes me as convoluted by comparison.

    Posted by venky kris on June 8 2006 2:06pm [Delete] [Edit]

    Just following up on Matt Ryan's Post

    Matt Ryan Writes :>>Here's a workaround for the update/subquery/cant do self >>table "bug"

    >>Senario is, ID 8 has multiple records, only the last >>(highest) record needs to be changed

    >>update t1 set c1 = 'NO'>>where id='8'>>order by recno desc limit 1

    You can also accomplish the same by the following query :

    update t1 , (select id ,max(recno) as recno from t1 where id=8 group by recno) ttset t1.c1 = 'NO'where tt.id=t1.id and t1.recno=tt.recno

    Comments are welcome.

    Posted by Paul Decowski on August 1 2006 9:43am [Delete] [Edit]

    Regarding Justin Swanhart's comment about retrieving a field's value in UPDATE query.

    > update some_table> set col = col + 1> where key = 'some_key_value'> and @value := col

    http://dev.mysql.com/doc/mysql/comment.php?id=7675&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html&action=deletehttp://dev.mysql.com/doc/mysql/comment.php?id=7675&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.htmlhttp://dev.mysql.com/doc/mysql/comment.php?id=7679&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html&action=deletehttp://dev.mysql.com/doc/mysql/comment.php?id=7679&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.htmlhttp://dev.mysql.com/doc/mysql/comment.php?id=7848&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html&action=deletehttp://dev.mysql.com/doc/mysql/comment.php?id=7848&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html

  • 1/29/2015 MySQL :: MySQL 5.0 Reference Manual :: 13.2.10 UPDATE Syntax

    http://dev.mysql.com/doc/refman/5.0/en/update.html 10/19

    > The @value := col will always evaluate to true and will store the col value before the update in the@value variable.

    In fact, in won't if `col` is NULL (0, empty string etc.) - then the condition is not met and the update querywon't be processed. The correct condition would be:

    AND ((@value := `col`) OR (1 = 1))

    It was very helpful to me anyway. Thx Justin!

    Posted by Barry Shantz on October 24 2006 9:40pm [Delete] [Edit]

    To update a column of a table with a rank based on subsets of data, the IF() function does a wonderfuljob.

    A summary table (in this case created to hold summary counts of other genealogy data, based on thetwo fields that make up the PRIMARY key) often contains unique key fields and one or more summarytotals (Cnt in this case). Additional ranking fields in the summary table can be easily updated to containrankings of the Cnt field using the IF function and local variables.

    Table DDL:

    CREATE TABLE `countsbyboth` (`SurnameID` int(11) unsigned NOT NULL default '0',`GedID` int(11) unsigned NOT NULL default '0',`Cnt` int(11) unsigned NOT NULL default '0',`sRank` int(11) unsigned NOT NULL default '0',`nRank` int(11) unsigned NOT NULL default '0',PRIMARY KEY (`SurnameID`,`GedID`),KEY `SurnameID` (`SurnameID`,`Cnt`),KEY `GedID` (`GedID`,`Cnt`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;

    After populating the table with rows containing key and summary data (and leaving the rank field(s) tobe updated ina subsequent step), the rank fields can be updated using syntax similar to the following:

    update countsbyboth set srank=0, nrank=0;set @rnk:=1, @gedid=0;update countsbybothset srank=if(@gedid=(@gedid:=gedid), (@rnk:=@rnk+1),(@rnk:=1))order by gedid desc, cnt desc;set @rnk:=1, @snmid=0;update countsbybothset nrank=if(@snmid=(@snmid:=surnameid), (@rnk:=@rnk+1),(@rnk:=1))order by surnameid desc, cnt desc;

    Query OK, 11752 rows affected (0.08 sec)Query OK, 0 rows affected (0.00 sec)Query OK, 11752 rows affected (0.24 sec)Query OK, 0 rows affected (0.00 sec)Query OK, 11752 rows affected (0.19 sec)

    It looks convoluted, but is really quite simple. The @rnk variable needs to be initialized, and the keyvalvariable (in this case @gedid or @snmid) needs to be set to a value that will not be matched by the firstrecord. The IF() function checks the previous key value (left side) against the current key value (rightside), and either increments the @rnk variable when the desired key value is the same as the previousrecords, or reset the @rnk variable to 1 when the key value changes.

    http://dev.mysql.com/doc/mysql/comment.php?id=8095&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html&action=deletehttp://dev.mysql.com/doc/mysql/comment.php?id=8095&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html

  • 1/29/2015 MySQL :: MySQL 5.0 Reference Manual :: 13.2.10 UPDATE Syntax

    http://dev.mysql.com/doc/refman/5.0/en/update.html 11/19

    This can be easily extended to accomodate ranking on more than one key value, and does not requiresub-selects that take considerable resources for a large table.

    This example intentionally assigns different ranks to equal values of Cnt for a given key, to facilitatereporting where column headings contain the rank value.

    Posted by Barry Shantz on October 24 2006 9:51pm [Delete] [Edit]

    In the previous example, if the @rnk value is initialed with set @rnk:=0rather thanset @rnk:=1 ,then it won't matter whether or not the first record's key value matches the 'key value' @gedid variable.

    Posted by Jon Meredith on October 31 2006 5:09pm [Delete] [Edit]

    Thanks for Justin Swanhart/Paul Decowski tip. As of 5.0.18 it looks like the optimiser has been improvedso the

    AND ((@value := `col`) OR (1 = 1))

    gets optimised out as 'true' and @value is left as NULL after the update.

    I got it to work again by rewriting as

    update some_tableset col = col + 1where key = 'some_key_value'and ((@value := col) IS NULL OR (@value := col) IS NOT NULL)

    So you get a true value either way and value will get set. Be careful what you put on the right-hand-sideas it could get evaluated twice.

    Posted by Dewey Gaedcke on December 27 2006 8:34pm [Delete] [Edit]

    Above in the docs, it says "you cannot update a table and select from the same table in a subquery"

    This is true but there are two simple ways around this limit.1) nest the subquery 2 deep so it is fully materialized before the update runs. For example:Update t1 set v1 = t3.v1 where id in(select t2.id, t2.v1 from (select id, v1 from t1) t2) t3

    2) use a self join rather than a subquery

    Posted by Lars Aronsson on March 9 2007 10:07pm [Delete] [Edit]

    Oracle databases has a keyword NOWAIT that can be used with UPDATE, causing the update to abortif it would get stuck waiting for locks. This keyword is not available in MySQL. Just letting you know, soyou can stop looking for it.

    Posted by John Batzel on March 16 2007 1:58pm [Delete] [Edit]

    The UPDATE 'bug' mentioned above is apparently related to upgrading from 4.x to 5.0x. The indexesare slightly different formats, and it breaks *some* things. myisamchk/check table won't fix this. Droppingand re-adding the indexes will. (And dumping the table to file and reloading it is just recreating theindexes with lots more IO than you need to do.)

    Posted by James Goatcher on March 16 2007 9:28pm [Delete] [Edit]

    This example/tip/bug-report uses MySQL version 5.0.19.

    When updating one table using values obtained from another table, the manual describes the "update

    http://dev.mysql.com/doc/mysql/comment.php?id=8096&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html&action=deletehttp://dev.mysql.com/doc/mysql/comment.php?id=8096&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.htmlhttp://dev.mysql.com/doc/mysql/comment.php?id=8131&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html&action=deletehttp://dev.mysql.com/doc/mysql/comment.php?id=8131&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.htmlhttp://dev.mysql.com/doc/mysql/comment.php?id=8279&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html&action=deletehttp://dev.mysql.com/doc/mysql/comment.php?id=8279&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.htmlhttp://dev.mysql.com/doc/mysql/comment.php?id=8454&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html&action=deletehttp://dev.mysql.com/doc/mysql/comment.php?id=8454&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.htmlhttp://dev.mysql.com/doc/mysql/comment.php?id=8470&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html&action=deletehttp://dev.mysql.com/doc/mysql/comment.php?id=8470&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.htmlhttp://dev.mysql.com/doc/mysql/comment.php?id=8472&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html&action=deletehttp://dev.mysql.com/doc/mysql/comment.php?id=8472&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html

  • 1/29/2015 MySQL :: MySQL 5.0 Reference Manual :: 13.2.10 UPDATE Syntax

    http://dev.mysql.com/doc/refman/5.0/en/update.html 12/19

    table1, table2" syntax, but does not delve into the correlated subquery approach very much. It alsodoes not point out a VERY important execution difference.

    Consider the following script:======================================================drop table if exists test_1;drop table if exists test_2;

    CREATE TABLE test_1 (col_pk integer NOT NULL,col_test integer);

    alter table test_1 add PRIMARY KEY (col_pk);

    CREATE TABLE test_2 (col_pk_join integer NOT NULL,col_test_new integer);

    insert into test_1 (col_pk, col_test) values ( 1, null );insert into test_1 (col_pk, col_test) values ( 2, null );commit;

    insert into test_2 (col_pk_join, col_test_new) values ( 1, 23 );insert into test_2 (col_pk_join, col_test_new) values ( 1, 34 );insert into test_2 (col_pk_join, col_test_new) values ( 2, 45 );commit;

    select * from test_1;select * from test_2;

    # This update should NOT work, but it does.UPDATE test_1 t,test_2 tmpset t.col_test = tmp.col_test_newwhere t.col_pk = tmp.col_pk_join;commit;

    select * from test_1;======================================================

    The output of the select and update statements is:

    +--------+----------+| col_pk | col_test |+--------+----------+| 1 | NULL || 2 | NULL |+--------+----------+

    2 rows in set

    +-------------+--------------+| col_pk_join | col_test_new |+-------------+--------------+| 1 | 23 || 1 | 34 |

  • 1/29/2015 MySQL :: MySQL 5.0 Reference Manual :: 13.2.10 UPDATE Syntax

    http://dev.mysql.com/doc/refman/5.0/en/update.html 13/19

    | 2 | 45 |+-------------+--------------+

    3 rows in set

    Query OK, 2 rows affectedRows matched: 2 Changed: 2 Warnings: 0

    Query OK, 0 rows affected

    +--------+----------+| col_pk | col_test |+--------+----------+| 1 | 23 || 2 | 45 |+--------+----------+

    2 rows in set

    Note that the update did NOT produce any errors or warnings. It should have. Why? Because a join onvalue 1 produces two values from table test_2. Two values cannot fit into a space for one. What MySQLdoes in this case is use the first value and ignore the second value. This is really bad in my opinionbecause it is, in essence, putting incorrect data into table test_1.

    Replace the update statement above with:UPDATE test_1 t1set t1.col_test = (select col_test_newfrom test_2 t2where t1.col_pk = t2.col_pk_join);

    This will produce the appropriate error for the given data:"ERROR 1242 : Subquery returns more than 1 row"and will not perform any update at all, which is good (it protects table test_1 from getting bad data).

    Now if you have different data........if you comment out one of the "1" values inserted into table test_2and use the correlated subquery update instead of the multi-table update, table test_1 will get updatedwith exactly what you expect.

    The moral of this example/tip/bug-report: do not use the multi-table update. Use the correlatedsubquery update instead. It's safe. If you keep getting an error when you think you shouldn't, you eitherhave bad data in your source table or you need to rework your subquery such that it produces aguaranteed one-row result for each destination row being updated.

    The reason I call the multi-table update a bug is simply because I feel it should produce the same orsimilar error as the correlated subquery update. My hope is that MySQL AB will agree with me.

    Posted by Luciano Fantuzzi on March 23 2007 2:32am [Delete] [Edit]

    Este sencillo script permite recrear el indice de una columna de forma automatica. Nota: Si una columna tiene una restriccion NOT NULL, sera necesario usar primero 'ALTER TABLE'para quitarle temporalmente la restriccion.

    /* INICIO del script */

    #En caso de tener con NOT NULL alguna columna (Ejemplo)ALTER TABLE MiTabla CHANGE columna

    http://dev.mysql.com/doc/mysql/comment.php?id=8478&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html&action=deletehttp://dev.mysql.com/doc/mysql/comment.php?id=8478&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html

  • 1/29/2015 MySQL :: MySQL 5.0 Reference Manual :: 13.2.10 UPDATE Syntax

    http://dev.mysql.com/doc/refman/5.0/en/update.html 14/19

    columna MEDIUMINT UNSIGNED DEFAULT NULL;

    #Cambio todos los valores a NULL (para que no haya riesgo de valores duplicados con restriccionesUNIQUE)UPDATE MiTabla SET columna=NULL;

    #Declaro una variable como contador (puede ser 1,2,3... o el num desde donde queremos empezar)SET @c:=1;

    #ConsultaUPDATE MiTabla SET columna=(SELECT @c:=@c+1);

    #Ahora podemos usar ALTER TABLE nuevamente si queremos cambiar la columna a NOT NULL (encaso de que la hayamos cambiado)

    /* FIN del script */

    Tengan en cuenta de que los indices principales (los declarados como PRIMARY KEY, por ejemplo, olos que se usan para linquear tablas) NO DEBERIAN CAMBIARSE, ya que se estropearian los vinculosentre las tablas! Esto podria evitarse declarando las claves foraneas (FOREIGN KEY) de las tablas delinqueo con el valor ON UPDATE CASCADE (lo que al actualizar los indices refrescaria los links entrelas tablas).

    Posted by Marc Vos on July 18 2007 1:15pm [Delete] [Edit]

    Here's the easy way to update a column in a table using values from other tables.

    update db1.a, (select distinct b.col1, b.col2from db2.b, db2.c, db2.dwhere b.col1'' and d.idnr=b.idnr and c.user=d.user and c.role='S'order by b.col1) as eset a.col1 = e.col1where a.idnr = e.col1

    The point is that every select statement returns a table. Name the result and you can access itscolumns. In this example I called the result 'e'.

    Posted by Richard Bronosky on September 5 2007 5:05pm [Delete] [Edit]

    Marc Vos led me to a solution to a problem that has been troubling me for a long time. As a DBA I oftenhave to support application developers who need to have data I control presented in a specific manner.This always results in a table based on their needs and populating the columns with data from existingtables. Usually it something like 15 columns from table A, 5 from table B, 30 from table c, and 230 fromtable d. In the past I have done this with either a series of "create temporary table t1 as select ... join ..."statements until I get the right set of columns.

    I never could figure out how to set the value of multiple columns with nesting a select statementdedicated to each column. Now I've got it. I'm attaching a transcript of doing it both ways. Thestatements use the tables that already exist in the mysql schema (at least in 5.0), so you can easilyrecreate this on your box in a test schema.

    --------------DROP TABLE IF EXISTS test--------------

    Query OK, 0 rows affected (0.00 sec)

    --------------CREATE TABLE test (t_id INT,k_id INT, t_name CHAR(64), t_desc TEXT) AS

    http://dev.mysql.com/doc/mysql/comment.php?id=8759&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html&action=deletehttp://dev.mysql.com/doc/mysql/comment.php?id=8759&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.htmlhttp://dev.mysql.com/doc/mysql/comment.php?id=8820&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html&action=deletehttp://dev.mysql.com/doc/mysql/comment.php?id=8820&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html

  • 1/29/2015 MySQL :: MySQL 5.0 Reference Manual :: 13.2.10 UPDATE Syntax

    http://dev.mysql.com/doc/refman/5.0/en/update.html 15/19

    SELECT help_topic_id AS t_id, help_keyword_id AS k_id, NULL AS t_name, NULL AS t_desc FROMmysql.help_relation LIMIT 10--------------

    Query OK, 10 rows affected (0.01 sec)Records: 10 Duplicates: 0 Warnings: 0

    --------------SELECT * FROM test--------------

    +------+------+--------+--------+| t_id | k_id | t_name | t_desc |+------+------+--------+--------+| 0 | 0 | NULL | NULL | | 327 | 0 | NULL | NULL | | 208 | 1 | NULL | NULL | | 409 | 2 | NULL | NULL | | 36 | 3 | NULL | NULL | | 388 | 3 | NULL | NULL | | 189 | 4 | NULL | NULL | | 169 | 5 | NULL | NULL | | 393 | 6 | NULL | NULL | | 17 | 7 | NULL | NULL | +------+------+--------+--------+

    10 rows in set (0.00 sec)

    --------------######## This is the elegant single select solution! ########UPDATE test AS t, (SELECT * FROM mysql.help_topic) AS h SETt.t_name=h.name,t.t_desc=substr(h.url,1-locate('/',reverse(h.url)))WHERE t.t_id=h.help_topic_id--------------

    Query OK, 10 rows affected (0.04 sec)Rows matched: 10 Changed: 10 Warnings: 0

    --------------SELECT * FROM test--------------

    +------+------+------------------+---------------------------+| t_id | k_id | t_name | t_desc |+------+------+------------------+---------------------------+| 0 | 0 | JOIN | join.html | | 327 | 0 | SELECT | select.html | | 208 | 1 | REPEAT LOOP | repeat-statement.html | | 409 | 2 | ISOLATION | set-transaction.html | | 36 | 3 | REPLACE INTO | replace.html | | 388 | 3 | LOAD DATA | load-data.html | | 189 | 4 | CREATE FUNCTION | create-function.html | | 169 | 5 | CHANGE MASTER TO | change-master-to.html | | 393 | 6 | CHAR | string-type-overview.html |

  • 1/29/2015 MySQL :: MySQL 5.0 Reference Manual :: 13.2.10 UPDATE Syntax

    http://dev.mysql.com/doc/refman/5.0/en/update.html 16/19

    | 17 | 7 | SHOW COLUMNS | show-columns.html | +------+------+------------------+---------------------------+

    10 rows in set (0.03 sec)

    --------------DROP TABLE IF EXISTS test--------------

    Query OK, 0 rows affected (0.00 sec)

    --------------CREATE TABLE test (t_id INT,k_id INT, t_name CHAR(64), t_desc TEXT) ASSELECT help_topic_id AS t_id, help_keyword_id AS k_id, NULL AS t_name, NULL AS t_desc FROMmysql.help_relation LIMIT 10--------------

    Query OK, 10 rows affected (0.01 sec)Records: 10 Duplicates: 0 Warnings: 0

    --------------SELECT * FROM test--------------

    +------+------+--------+--------+| t_id | k_id | t_name | t_desc |+------+------+--------+--------+| 0 | 0 | NULL | NULL | | 327 | 0 | NULL | NULL | | 208 | 1 | NULL | NULL | | 409 | 2 | NULL | NULL | | 36 | 3 | NULL | NULL | | 388 | 3 | NULL | NULL | | 189 | 4 | NULL | NULL | | 169 | 5 | NULL | NULL | | 393 | 6 | NULL | NULL | | 17 | 7 | NULL | NULL | +------+------+--------+--------+

    10 rows in set (0.00 sec)

    --------------######## This is the nasty one select for each column that needs to be updated method! ########UPDATE test AS t SETt.t_name=(SELECT name FROM mysql.help_topic WHERE t.t_id=help_topic_id),t.t_desc=(SELECT substr(url,1-locate('/',reverse(url))) FROM mysql.help_topic WHEREt.t_id=help_topic_id)--------------

    Query OK, 10 rows affected (0.00 sec)Rows matched: 10 Changed: 10 Warnings: 0

    --------------SELECT * FROM test--------------

  • 1/29/2015 MySQL :: MySQL 5.0 Reference Manual :: 13.2.10 UPDATE Syntax

    http://dev.mysql.com/doc/refman/5.0/en/update.html 17/19

    +------+------+------------------+---------------------------+| t_id | k_id | t_name | t_desc |+------+------+------------------+---------------------------+| 0 | 0 | JOIN | join.html | | 327 | 0 | SELECT | select.html | | 208 | 1 | REPEAT LOOP | repeat-statement.html | | 409 | 2 | ISOLATION | set-transaction.html | | 36 | 3 | REPLACE INTO | replace.html | | 388 | 3 | LOAD DATA | load-data.html | | 189 | 4 | CREATE FUNCTION | create-function.html | | 169 | 5 | CHANGE MASTER TO | change-master-to.html | | 393 | 6 | CHAR | string-type-overview.html | | 17 | 7 | SHOW COLUMNS | show-columns.html | +------+------+------------------+---------------------------+

    10 rows in set (0.00 sec)

    Bye

    Posted by Joris Kinable on April 30 2008 9:34am [Delete] [Edit]

    Updating multiple fields based on query results can be quite expensive if the same query has to beexecuted multiple times. Imagine the following table:

    summary(X,A,B,C,D) and a query which returns: (X,E,F) and you want to update the summary tablefields C and D with the values of E and F:

    Summary: (1,2,3,0,0),(10,12,13,0,0) and query result: (1,4,5),(10,14,15) should result in the updatedsummary table: (1,2,3,4,5,6),(10,11,12,13,14,15)

    BAD SOLUTION (same query is evaluated twice!):

    UPDATE summary SET C=(SELECT E FROM (query) q WHERE summary.X=q.X), D=(SELECT F FROM(query) q WHERE summary.X=q.X)

    GOOD SOLUTION (query is only evaluated once):

    UPDATE summary AS t, (query) AS q SET t.C=q.E, t.D=q.F WHERE t.X=q.X

    Posted by Nigel Smith on September 16 2008 9:31am [Delete] [Edit]

    Example of updating a table using a group selection from another table:-update tableA,(select idTableA,min(valueField) as minV from tableB group by idTableA) as Tset tableA.minValue=minV where tableA.idTableA=T.idTableA

    Posted by Roger Morris on September 23 2008 4:04am [Delete] [Edit]

    To swap two values in a single table. If you need to keep the lower value in a certain column:mysql> select * from test;

    +-------+------+-------+-------+| index | name | item1 | item2 |+-------+------+-------+-------+| 1 | one | 25 | 50 | | 2 | two | 75 | 40 | | 3 | one | 35 | 60 |

    http://dev.mysql.com/doc/mysql/comment.php?id=9443&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html&action=deletehttp://dev.mysql.com/doc/mysql/comment.php?id=9443&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.htmlhttp://dev.mysql.com/doc/mysql/comment.php?id=9723&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html&action=deletehttp://dev.mysql.com/doc/mysql/comment.php?id=9723&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.htmlhttp://dev.mysql.com/doc/mysql/comment.php?id=9736&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html&action=deletehttp://dev.mysql.com/doc/mysql/comment.php?id=9736&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html

  • 1/29/2015 MySQL :: MySQL 5.0 Reference Manual :: 13.2.10 UPDATE Syntax

    http://dev.mysql.com/doc/refman/5.0/en/update.html 18/19

    | 4 | four | 100 | 80 | +-------+------+-------+-------+

    4 rows in set (0.00 sec)

    ### (@olditem1:=item1) will assign the value of item1 *before* the update.

    mysql> update test set item1=item2,item2=@olditem1 where (@olditem1:=item1) and item1>item2;Query OK, 2 rows affected (0.00 sec)Rows matched: 2 Changed: 2 Warnings: 0

    mysql> select * from test;

    +-------+------+-------+-------+| index | name | item1 | item2 |+-------+------+-------+-------+| 1 | one | 25 | 50 | | 2 | two | 40 | 75 | | 3 | one | 35 | 60 | | 4 | four | 80 | 100 | +-------+------+-------+-------+

    4 rows in set (0.00 sec)

    Posted by Enrico Modanese on September 2 2009 7:48am [Delete] [Edit]

    Following the post of James Goatcher (object: ORDER BY in multi-table UPDATE) I'd like to resume theargument and related work-around:

    1. multi-table UPDATE doesn't support ORDER BY (as written in documentation)

    2. multi-table UPDATE retrieving more than 1 row for every row to be updated, will perform only 1update with the first found value and wont send any message about following skipped values (I don'tknow if it should be called an error)

    3. first work-around (+quick -secure): be sure that the joined tables are ordered to offer as first thecorrect value

    4. second work-around (-quick +secure): use a subselect for the value to be set [ x=(SELECT yy FROM... ORDER BY... LIMIT 1) ] as shown in the preceding example of James Goatcher (please note the useof LIMIT)

    Hope this will help, Enrico

    Posted by Pavel Tishkin on January 26 2010 7:39pm [Delete] [Edit]

    UPDATE some_table as bmSET bm.i_ordi=(SELECT @a:=@a+1)WHERE bm.i_type=1 AND (@a:=IFNULL(@a,-2)+1)'1'ORDER BY bm.i_create_ts;

    Sorting AND set auto_increment order

    Posted by Anto Justus on June 2 2010 9:46am [Delete] [Edit]

    you can try this type of query :

    UPDATE dt_log AS t, (

    http://dev.mysql.com/doc/mysql/comment.php?id=10357&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html&action=deletehttp://dev.mysql.com/doc/mysql/comment.php?id=10357&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.htmlhttp://dev.mysql.com/doc/mysql/comment.php?id=10593&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html&action=deletehttp://dev.mysql.com/doc/mysql/comment.php?id=10593&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.htmlhttp://dev.mysql.com/doc/mysql/comment.php?id=10776&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html&action=deletehttp://dev.mysql.com/doc/mysql/comment.php?id=10776&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html

  • 1/29/2015 MySQL :: MySQL 5.0 Reference Manual :: 13.2.10 UPDATE Syntax

    http://dev.mysql.com/doc/refman/5.0/en/update.html 19/19

    SELECT max(el_count)+1 as maxcount FROM dt_log where dt_nameid IN ('1','2','3','4') ) AS h SET t.dt_rej = h.maxcountWHERE t.dt_edate = '0000-00-00 00:00:00' AND t.dt_nameid IN ('1','2','3','4')

    get the max and update..

    Posted by Dave Scotese on October 11 2010 11:49pm [Delete] [Edit]

    When I executed a correlated subquery:

    UPDATE T1 SET f1= (SELECT COUNT(*) FROM T2 WHERE T2.f2=T1.f2)

    to update one table with aggregates from another, it took 3 seconds to do 50 records and about 57seconds to do 800 records.

    When I used a non-correlated subquery:

    UPDATE T1 INNER JOIN (SELECT COUNT(*) AS c FROM T2 GROUP BY f2) t USING(f2) SET f1=t.c

    it did 76 records in 177 ms, and 350 records in 177 ms and 2800 records in 250 ms.

    I believe that a correlated subquery is executed once for each result of the outer query, whereas a JOINto a non-correlated subquery executes the inner query only once.

    Posted by Misha B on April 21 2011 4:49pm [Delete] [Edit]

    Change values between two and more columns. In result, ufter update, columns will have values fromafter columnscolumn1 = column2, column2 = column1

    UPDATEtable1SETcolumn1 = (@v := column1), column1 = column2, column2 = @v;

    Posted by Ajmer Phull on February 2 2012 7:24am [Delete] [Edit]

    Hopefully this will be useful to someone else, like it was for me when I had to perform data cleansing andenhancing badly designed databases. This can also be helpful for replacing data in fields with ID's whennormalising databases.

    The following will update a field (field9 which is empty) in TABLE1 with data from a field (field9) inTABLE3 using joins with TABLE2 and TABLE3. I have made up the WHERE & AND conditions to showthis example.

    UPDATE table1 t1 JOIN table2 t2 ON t1.field1 = t2.field1 JOIN table3 t3 ON (t3.field1=t2.field2 AND t3.field3 IS NOT NULL) SET t1.field9=t3.field9WHERE t1.field5=1AND t1.field9 IS NULL

    Add your own comment

    Top / Previous / Next / Up / Table of Contents

    2015, Oracle Corporation and/or its affiliates

    http://dev.mysql.com/doc/mysql/comment.php?id=11525&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html&action=deletehttp://dev.mysql.com/doc/mysql/comment.php?id=11525&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.htmlhttp://dev.mysql.com/doc/mysql/comment.php?id=11836&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html&action=deletehttp://dev.mysql.com/doc/mysql/comment.php?id=11836&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.htmlhttp://dev.mysql.com/doc/mysql/comment.php?id=12165&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.html&action=deletehttp://dev.mysql.com/doc/mysql/comment.php?id=12165&return=%2Fdoc%2Frefman%2F5.0%2Fen%2Fupdate.htmlhttp://dev.mysql.com/doc/refman/5.0/en/rewriting-subqueries.htmlhttp://dev.mysql.com/doc/refman/5.0/en/sql-syntax-transactions.htmlhttp://dev.mysql.com/doc/refman/5.0/en/sql-syntax-data-manipulation.htmlhttp://dev.mysql.com/doc/refman/5.0/en/index.htmlhttp://www.oracle.com/