SELECT
HANDLER
INSERT
INSERT DELAYED
UPDATE
DELETE
TRUNCATE
REPLACE
LOAD DATA INFILE
DO
Buy this Reference Manual in softcover from Barnes & Noble!
UPDATE
UPDATE [LOW_PRIORITY] [IGNORE] tbl_name SET col_name1=expr1 [, col_name2=expr2, ...] [WHERE where_definition] [LIMIT #]
Оператор UPDATE
обновляет столбцы в соответствии с их новыми значениями в строках существующей таблицы. В выражении SET
указывается, какие именно столбцы следует модифицировать и какие величины должны быть в них установлены. В выражении WHERE
, если оно присутствует, задается, какие строки подлежат обновлению. В остальных случаях обновляются все строки. Если задано выражение ORDER BY
, то строки будут обновляться в указанном в нем порядке.
Если указывается ключевое слово LOW_PRIORITY
, то выполнение данной команды UPDATE
задерживается до тех пор, пока другие клиенты не завершат чтение этой таблицы.
Если указывается ключевое слово IGNORE
, то команда обновления не будет прервана, даже если при обновлении возникнет ошибка дублирования ключей. Строки, из-за которых возникают конфликтные ситуации, обновлены не будут.
Если доступ к столбцу из указанного выражения осуществляется по аргументу tbl_name
, то команда UPDATE
использует для этого столбца его текущее значение. Например, следующая команда устанавливает столбец age
в значение, на единицу большее его текущей величины:
mysql> UPDATE persondata SET age=age+1;
Значения команда UPDATE
присваивает слева направо. Например, следующая команда дублирует столбец age
, затем инкрементирует его:
mysql> UPDATE persondata SET age=age*2, age=age+1;
Если столбец устанавливается в его текущее значение, то MySQL замечает это и не обновляет его.
Команда UPDATE
возвращает количество фактически измененных строк. В версии MySQL 3.22 и более поздних функция C API mysql_info()
возвращает количество строк, которые были найдены и обновлены, и количество предупреждений, имевших место при выполнении UPDATE
.
В версии MySQL 3.23 можно использовать LIMIT #
, чтобы убедиться, что было изменено только заданное количество строк.
Posted by [name withheld] on Monday August 19 2002, @1:53pm | [Delete] [Edit] |
You can get around problems of table names by
quoting them, as phpMyAdmin does by default. The
appropriate quotes to use are the backticks ``,
such as you use on the unix commandline to cause
execution and are also used to accent characters.
Posted by on Friday September 6 2002, @7:23am | [Delete] [Edit] |
A simple update example, a spelling mistake in table patrons, field urlimage. The name was mispelled 'Critall':
update patrons set urlimage='/library/digiphoto/barbcrittall.jpg' where lastname like 'Crittal%';
Posted by on Saturday September 14 2002, @12:04pm | [Delete] [Edit] |
A word of advice to new users. Read the manual
regarding reserved words in table names. You can
get around it in newer version by qouting the table
name, but it's generaly not a good idea to use words
like select, update, insert etc.. as table and column
names.
Posted by on Tuesday September 24 2002, @11:24am | [Delete] [Edit] |
UPDATE a table from another table : A simple
example I've looked for at least 5 times and have
had to relearn every time --
Q -- I've got students.id, students.class_id and
classes.class_id, classes.count_of_students
I want to count the number of times each class_id
shows up in the students table and put it in the
record for that class in the classes table. (Just to
make sure my incrementing process is working right
in my front end.)
A -- CREATE TABLE s_counts SELECT class_id, count
(class_id) as count
FROM students GROUP BY class_id.......CREATE
TABLE new_classes SELECT c.class_id, s.count FROM
classes as c, s_counts as s WHERE c.class_id =
s.class_id.....ALTER TABLE classes RENAME
classes_old
..... ALTER TABLE new_classes RENAME classes .....
This scoop, switch, drop works to UPDATE a table
from another table.... but is this the "professional"
or "accepted"
way to do it?
Posted by Scott Leonard on Tuesday October 29 2002, @12:02pm | [Delete] [Edit] |
I suggest everyone stay away from reserved words
as table names. The best way to do so is to add a
simple prefix to your table name and keep the
field names simple too. user, email, pass, uid,
pid, sid... etc. Don't use count as a table name
or field name.
Rule of thumb: verbs are not nouns: use a noun for
your table name and make it a proper one. :)
Posted by AJIT DIXIT on Monday November 25 2002, @7:04am | [Delete] [Edit] |
Multi-Table update works fine If I set connection
as root user
My Query is " update Stockists, areas set a_nm =
aname where acd = area " Works fine with root user
connection
If I want to work with non-root user I get error
update command denied to user: 'aldixit@localhost'
for table 'areas'
The user has all required previledges and can
update these tables individually
What are previledges required for multi-table update ?
I am working on mysql-4.0.5a
Posted by PJ Kix on Thursday December 5 2002, @4:03am | [Delete] [Edit] |
Don't forget that if you have a timestamp column
and you issue an UPDATE query, the timestamp will
automagically get updated as well. Don't get burned.
-=PJK=-
Posted by on Monday December 9 2002, @2:07pm | [Delete] [Edit] |
For those who can't yet move to MySQL 4.x, here's
a workaround for multi-table UPDATEs for tables
*without* auto-incrementing columns, but *with* a
primary key: having created a separate table with
identical columns; INSERT rows into the separate
table, SELECTing from a joined query; REPLACE into
the original table FROM the separate table; DELETE
the rows from the separate table. (An) additional
column(s) in the separate table will allow you to
distinguish between simultaneous "UPDATEs" from
different users.
Posted by on Wednesday February 26 2003, @2:00am | [Delete] [Edit] |
UPDATE tips:-
1) When using multiple tables having a 1-to-many relationship, UPDATE selects the FIRST qualifying match.
2) If you need to use aggregate functions you will need to use INSERT to create another table, then use UPDATE to set the values in the table you wish to ... er... update.
Posted by Alon Shalita on Wednesday March 5 2003, @3:29am | [Delete] [Edit] |
While doing a multy table update I got this message:
update command denied to user: 'alon@localhost'
for table 'details'.
The privileges were set right (as far as I know), and
doing the same operation as root worked well.
It seems like a bug, an upgrade from 4.0.6 to 4.0.11 solved
the problem.
Posted by Nick Ferreri on Monday March 10 2003, @12:17pm | [Delete] [Edit] |
I'm having problems doing a multi table update. Any idea why this wouldn't work?
UPDATE userfield,user SET userfield.field7='Yes' WHERE user.userid=userfield.userid and user.usergroupid=5
getting this error:
You have an error in your SQL syntax near ' user set userfield.field7='Yes' where user.userid=userfield.userid and user.use' at line 1
Almost looks like it isn't recognizing the second table. I'm using PHP 4.2.2
Add your own comment.