Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This is the sequence solution (for postgres), you'd have to do it in a stored procedure or on your application code, of course.</p> <pre><code>postgres=# create table foo(id serial primary key, text varchar); NOTICE: CREATE TABLE will create implicit sequence "foo_id_seq" for serial column "foo.id" NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "foo_pkey" for table "foo" CREATE TABLE postgres=# create table bar(id int references foo, text varchar); CREATE TABLE postgres=# select nextval('foo_id_seq'); nextval --------- 1 (1 row) postgres=# insert into foo values (1,'a'); insert into bar values(1,'b'); INSERT 0 1 INSERT 0 1 </code></pre> <p>For <a href="http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html" rel="nofollow noreferrer">MySQL</a>, the transaction is important not to trip on your own feet in case you're using the same connection for more than one insert.</p> <blockquote> <p>For LAST_INSERT_ID(), the most recently generated ID is maintained in the server on a per-connection basis. It is not changed by another client. It is not even changed if you update another AUTO_INCREMENT column with a non-magic value (that is, a value that is not NULL and not 0). Using LAST_INSERT_ID() and AUTO_INCREMENT columns simultaneously from multiple clients is perfectly valid. Each client will receive the last inserted ID for the last statement that client executed.</p> </blockquote> <pre><code>mysql&gt; create table foo(id int primary key auto_increment, text varchar(10)) Engine=InnoDB; Query OK, 0 rows affected (0.06 sec) mysql&gt; create table bar(id int references foo, text varchar(10)) Engine=InnoDB; Query OK, 0 rows affected (0.01 sec) mysql&gt; begin; Query OK, 0 rows affected (0.00 sec) mysql&gt; insert into foo(text) values ('x'); Query OK, 1 row affected (0.00 sec) mysql&gt; insert into bar values (last_insert_id(),'y'); Query OK, 1 row affected (0.00 sec) mysql&gt; commit; Query OK, 0 rows affected (0.04 sec) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload