Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL: How can I create a new row and get the new id without inserting data?

Tags:

mysql

Normally I get a new ID by inserting some data and it creates a new row and returns the new ID. But if I dont want to insert any data I just want to create a new row with a new ID and get the new ID...how can I do that?

Thanks.

UPDATE:

OK Here is my issue. The table I wanted to do this to only has the 1 ID column. Why? I'll explain (we'll I'll try to). I have another table where each row has its own unique ID variation_id (auto-inc), but each row needs to be tied to a group of other rows from the same table. I have another column called group_id I can't have it auto-inc because it needs to appear multiple times, it his what says which variations should be grouped together. So I wanted to have a second table with group_id as the primary key and auto-inc so I could use that to generate the new group_id whenever I need a new group. I guess I am going about this the wrong way....so what should I do?

like image 735
JD Isaacks Avatar asked Apr 28 '09 18:04

JD Isaacks


People also ask

How do you create a new row in MySQL?

When inserting a single row into the MySQL table, the syntax is as follows: INSERT INTO table_name(column_1,column_2,column_3) VALUES (value_1,value_2,value_3); In the INSERT INTO query, you should specify the following information: table_name : A MySQL table to which you want to add a new row.

How can I get auto increment ID?

To get the next auto increment id in MySQL, we can use the function last_insert_id() from MySQL or auto_increment with SELECT. Creating a table, with “id” as auto-increment. Inserting records into the table. To display all the records.

How can I get current ID in MySQL?

$id = intval($_GET['id']);

How do you insert if row does not exist in MySQL?

There are three ways you can perform an “insert if not exists” query in MySQL: Using the INSERT IGNORE statement. Using the ON DUPLICATE KEY UPDATE clause. Or using the REPLACE statement.


2 Answers

here is an example:

CREATE TABLE X (id int PRIMARY KEY AUTO_INCREMENT);

then you can "feed" your table with:

INSERT INTO X (id) VALUES (NULL);
SELECT LAST_INSERT_ID();

Check this fiddle: http://sqlfiddle.com/#!2/6b19c/1

Hope it helps!

Тарас Лукавий did another question and here's the answer:

CREATE TABLE X (id int PRIMARY KEY AUTO_INCREMENT, time timestamp);

then you "feed" data with:

INSERT INTO X (id, time) VALUES (NULL, now());
SELECT LAST_INSERT_ID();

Now, let's check it:

SELECT * FROM X

You'll see every row with automatic id and timestamp.

Check this fiddle: http://sqlfiddle.com/#!2/9a344/2

Hope it helps!

like image 100
pcsi Avatar answered Oct 19 '22 09:10

pcsi


All your columns would have to be nullable, and you'd have to insert null for all the other columns but ID.

like image 29
Parrots Avatar answered Oct 19 '22 11:10

Parrots