SELECT
HANDLER
INSERT
INSERT DELAYED
UPDATE
DELETE
TRUNCATE
REPLACE
LOAD DATA INFILE
DO
Buy this Reference Manual in softcover from Barnes & Noble!
INSERT
INSERT [LOW_PRIORITY | DELAYED] [IGNORE] [INTO] tbl_name [(col_name,...)] VALUES (expression,...),(...),... или INSERT [LOW_PRIORITY | DELAYED] [IGNORE] [INTO] tbl_name [(col_name,...)] SELECT ... или INSERT [LOW_PRIORITY | DELAYED] [IGNORE] [INTO] tbl_name SET col_name=expression, col_name=expression, ...
Оператор INSERT
вставляет новые строки в существующую таблицу. Форма данной команды INSERT ... VALUES
вставляет строки в соответствии с точно указанными в команде значениями. Форма INSERT ... SELECT
вставляет строки, выбранные из другой таблицы или таблиц. Форма INSERT ... VALUES
со списком из нескольких значений поддерживается в версии MySQL 3.22.5 и более поздних. Синтаксис выражения col_name=expression
поддерживается в версии MySQL 3.22.10 и более поздних.
tbl_name
задает таблицу, в которую должны быть внесены строки. Столбцы, для которых заданы величины в команде, указываются в списке имен столбцов или в части SET
:
INSERT ... VALUES
или INSERT ... SELECT
, то величины для всех столбцов должны быть определены в списке VALUES()
или в результате работы SELECT
. Если порядок столбцов в таблице неизвестен, для его получения можно использовать DESCRIBE tbl_name
.CREATE TABLE
. В MySQL всегда предусмотрено значение по умолчанию для каждого поля. Это требование ``навязано'' MySQL, чтобы обеспечить возможность работы как с таблицами, поддерживающими транзакции, так и с таблицами, не поддерживающими их. Наша точка зрения (разработчиков) состоит в том, что проверка содержимого полей должна производиться приложением, а не сервером баз данных.expression
может относится к любому столбцу, который ранее был внесен в список значений. Например, можно указать следующее:
mysql> INSERT INTO tbl_name (col1,col2) VALUES(15,col1*2);Но нельзя указать:
mysql> INSERT INTO tbl_name (col1,col2) VALUES(col2*2,15);
LOW_PRIORITY
, то выполнение данной команды INSERT
будет задержано до тех пор, пока другие клиенты не завершат чтение этой таблицы. В этом случае данный клиент должен ожидать, пока данная команда вставки не будет завершена, что в случае интенсивного использования таблицы может потребовать значительного времени. В противоположность этому команда INSERT DELAYED
позволяет данному клиенту продолжать операцию сразу же. See section 6.4.4 Синтаксис оператора INSERT DELAYED
. Следует отметить, что указатель LOW_PRIORITY
обычно не используется с таблицами MyISAM
, поскольку при его указании становятся невозможными параллельные вставки. See section 7.1 Таблицы MyISAM.INSERT
со строками, имеющими много значений, указывается ключевое слово IGNORE
, то все строки, имеющие дублирующиеся ключи PRIMARY
или UNIQUE
в этой таблице, будут проигнорированы и не будут внесены. Если не указывать IGNORE
, то данная операция вставки прекращается при обнаружении строки, имеющей дублирующееся значение существующего ключа. Количество строк, внесенных в данную таблицу, можно определить при помощи функции C API mysql_info()
.DONT_USE_DEFAULT_FIELDS
, то команда INSERT
будет генерировать ошибку, если явно не указать величины для всех столбцов, которые требуют значений не-NULL
. See section 2.3.3 Типичные опции configure
.mysql_insert_id
можно найти величину, использованную для столбца AUTO_INCREMENT
. See section 8.4.3.126 mysql_insert_id()
.Если задается команда INSERT ... SELECT
или INSERT ... VALUES
со списками из нескольких значений, то для получения информации о данном запросе можно использовать функцию C API mysql_info()
. Формат этой информационной строки приведен ниже:
Records: 100 Duplicates: 0 Warnings: 0
Duplicates
показывает число строк, которые не могли быть внесены, поскольку они дублировали бы значения некоторых существующих уникальных индексов. Указатель Warnings
показывает число попыток внести величину в столбец, который по какой-либо причине оказался проблематичным. Предупреждения возникают при выполнении любого из следующих условий:
NULL
в столбец, который был объявлен, как NOT NULL
. Данный столбец устанавливается в значение, заданное по умолчанию.'10.34 a'
. Конечные данные удаляются и вносится только оставшаяся числовая часть. Если величина вовсе не имеет смысла как число, то столбец устанавливается в 0
.CHAR
, VARCHAR
, TEXT
или BLOB
строки, превосходящей максимальную длину столбца. Данная величина усекается до максимальной длины столбца.Posted by on Wednesday December 18 2002, @5:27pm | [Delete] [Edit] |
This page states that you can use a previously
inserted column to help define a new column, in its
example. However, it seems that auto_increment
columns aren't defined until after the rest of the
query is evaluated. This makes sense, as it wouldn't
assign an auto_increment value until the parser has
verified that the query is valid, but it means that you
can't use an auto_increment column to help define
subsequent columns. For example:
INSERT INTO `table` (id,sentence) VALUES(NULL,
concat('The id is ',id))
Even though the id column is listed first and is
evaluated first, a value is not inserted into it until the
rest of the query is evaluated, so the sentence
column would always contain the string 'The id is 0'.
Posted by Charles Gregory on Friday September 20 2002, @12:10pm | [Delete] [Edit] |
If you encounter "ERROR 1036: Table 'xxx' is read
only", this may be due to a corrupt internal setting in
MySQL. This can occur if, for example, you upload a
new table from a Windows-based MySQL database
directly to a Linux/Unix database. The solution is to
use 'dumpmysql' to dump the databases, THEN be
sure to DROP TABLE for the 'read only tables' or the
internal config will not be properly reset! Deleting the
table files is not sufficient. Once the tables are
dropped, feed the dump file back to mysql, and it will
create the tables anew, and they will be writable.
Posted by Joshua Mostafa on Wednesday November 13 2002, @9:17pm | [Delete] [Edit] |
Regarding the use of reserved words in table names:
much better than the use of backticks is the
complete avoidance of reserved word usage. The
same goes for spaces in table names (another
scenario which calls for the use of backticks):
generally a bad idea, especially when the use of
backticks could cause potentially cause collision with
their use in scripting language, eg the execution
operator in Perl or PHP (the backtick).
Posted by on Wednesday December 18 2002, @5:29pm | [Delete] [Edit] |
Ever wanted to copy a table record within
the same table?
Here's how to create a new copy of an existing
record for any kind of table, regardless of the
number of columns or their type.
In this example we have a table called `media` with
a number of fields which we want to duplicate, and
one, ID, containing a unique ID which must
change.
On entry to the PHP (or other language) routine we
know the ID of the record we want to copy
($oldID), and we have generated another ID for the
new record ($newID).
Posted by Steve Yates on Wednesday December 18 2002, @5:29pm | [Delete] [Edit] |
Perhaps it's apparent but since there's not an
example, strings must be quoted when using
VALUES. Otherwise the server evidently interprets
the values as columns since an error message is
generated: "Unknown column 'firstvalue' in 'field
list'".Numbers do not have to be
quoted. Dates may or may not require quoting
based on their format (see "6.2.2.2 The DATETIME,
DATE, and TIMESTAMP Types"). NULLs must be
indicated as "NULL" values, not left blank.
Posted by [name withheld] on Wednesday December 18 2002, @5:29pm | [Delete] [Edit] |
Error 1036 Table tbl_name is read only.
Here is a new one for all you who have recieved this
error running MySql as a service on windows 2000.
When running the MySql server --standalone all
tables work fine, but when installed as a service all
the tables become read-only? After many hours of
troubleshooting i relized when i decided to reload
MySql and tried to DROP a database, that MySql did
not have file write permission to the hard drive under
Win2000. The FIX: go to
start=>programs=>administrative tools=>services
and go to properties of the MySql service (once
installed) select the log-on tab and choose "Log on
as this account: and put in the administrator log-on
information (or a user with file write permissions).
The Local System Account apperentlydoes not seem
to have that permission. Anyway it worked for me if
you should have this problem give it a try.
Posted by [name withheld] on Friday March 7 2003, @1:41pm | [Delete] [Edit] |
maybe running a service such as mysql as administrator isn't the best idea in the world, just an opinion (theres a reason it won't run as root generally in linux ;) )
Add your own comment.