Новости
Документация
Download
Webboard
Поиск
FAQ/ЧаВо
Обратная связь




MySQL.RU - Webboard



Вернуться
Результат запроса INSERT (Николай) 13/11/2005 - 00:42:07
      Re: Есть функция (bac) 13/11/2005 - 21:33:39
      Re: Есть функция (Николай) 14/11/2005 - 00:20:35
      Re: Есть функция (bac) 14/11/2005 - 02:26:24
      Re: Результат запроса INSERT (Libov) 14/11/2005 - 05:12:06

> Original message text:
> From: Николай - 13/11/2005 - 00:42:07
> Subject:Результат запроса INSERT
> -----------------
> Задачка вот какая: некоторые данные вставляются в таблицу. Естесственно, у строки есть id и естесственно он auto_increment. А потому в запросе передается null. А надо бы как-то узнать, какой id назначился строке, когда она добавилась, чтобы впихнуть его в другую таблицу... Решение с выборкой последней строки из таблицы из доставанием id из нее - не выход, т.к. вполне может получиться так, что после нужной в данный момент строки уже будут добавлены другие и вытащится не тот id, который нужен - запросов к базе много и происходят они часто.
> А потому нужен какой-то более хитрый вариант... Сам уже голову сломал :/
>


From: bac - 14/11/2005 - 02:26:24
Subject:Есть функция
-----------------
LAST_INSERT_ID() , LAST_INSERT_ID(expr)

Returns the last automatically generated value that was inserted into an AUTO_INCREMENT column.



mysql> SELECT LAST_INSERT_ID();
-> 195


The last ID that was generated is maintained in the server on a per-connection basis. This means the value the function returns to a given client is the most recent AUTO_INCREMENT value generated by that client. The value cannot be affected by other clients, even if they generate AUTO_INCREMENT values of their own. This behavior ensures that you can retrieve your own ID without concern for the activity of other clients, and without the need for locks or transactions.

The value of LAST_INSERT_ID() is not changed if you update the AUTO_INCREMENT column of a row with a non-magic value (that is, a value that is not NULL and not 0).

If you insert many rows at the same time with an insert statement, LAST_INSERT_ID() returns the value for the first inserted row. The reason for this is to make it possible to easily reproduce the same INSERT statement against some other server.

If you use INSERT IGNORE and the record is ignored, the AUTO_INCREMENT counter is not incremented and LAST_INSERT_ID() returns 0, which reflects that no record was inserted. (Before MySQL 4.1, AUTO_INCREMENT counter still is incremented and LAST_INSERT_ID() returns the new value.)

If expr is given as an argument to LAST_INSERT_ID(), the value of the argument is returned by the function and is remembered as the next value to be returned by LAST_INSERT_ID(). This can be used to simulate sequences:


Create a table to hold the sequence counter and initialize it:

mysql> CREATE TABLE sequence (id INT NOT NULL);
mysql> INSERT INTO sequence VALUES (0);

Use the table to generate sequence numbers like this:

mysql> UPDATE sequence SET id=LAST_INSERT_ID(id+1);
mysql> SELECT LAST_INSERT_ID();

The UPDATE statement increments the sequence counter and causes the next call to LAST_INSERT_ID() to return the updated value. The SELECT statement retrieves that value. The mysql_insert_id() C API function can also be used to get the value. See Section 24.2.3.33, “mysql_insert_id()”.


You can generate sequences without calling LAST_INSERT_ID(), but the utility of using the function this way is that the ID value is maintained in the server as the last automatically generated value. It is multi-user safe because multiple clients can issue the UPDATE statement and get their own sequence value with the SELECT statement (or mysql_insert_id()), without affecting or being affected by other clients that generate their own sequence values.

Note that mysql_insert_id() is only updated after INSERT and UPDATE statements, so you cannot use the C API function to retrieve the value for LAST_INSERT_ID(expr) after executing other SQL statements like SELECT or SET.






[Это сообщение - спам!]

Последние сообщения из форума

Уважаемые посетители форума MySQL.RU!
Убедительная просьба, прежде чем задавать свой вопрос в этом форуме, обратите внимание на разделы:
- ответы на наиболее часто задаваемые вопросы - FAQ
- раздел документация
- раздел поиск по сообщениям форума и документации
Также, старайтесь наиболее подробно указывать свою ситуацию (версию операционной системы, версию MySQL, версию программного обеспечения, по которому возникает вопрос, текст возникающих ошибок, и др.)
Помните, чем конкретнее Вы опишете ситуацию, тем больше шансов получить реальную помощь.
 Имя:
 E-mail:
 Тема:
 Текст:
Код подтверждения отправки: Code
25066



РЕКЛАМА НА САЙТЕ
  Создание сайтов | |