简体   繁体   中英

MySQL set value of addional field to auto_increment value

I have a table with an AUTO_INCREMENT id , this table also has a parent_id field. In certain cases, when the insert data is itself a parent and has no parent, I need to set the parent_id to the same value as its own id.

Is this possible with a single sql statement, or do I have to do a LAST_INSERT_ID and a separate update statement?

Thanks

You have to do in separated statements.

The tree system usually assumes '0' as root or father of no-father items or father of the first level items, and '0' not exists in database.

I recommend you not to set the same id of the item as parent of this item because... this item is his own father? you really need that?

It is technically possible, though I advise highly against it. The only way this query could work is if you can guarantee that no records will be deleted, and even still I say don't use it. But if you must...

INSERT INTO `table` (field1, field2, parent_id)
VALUES('data1', 'data2', 
            (SELECT id FROM (SELECT max(id) AS id FROM `table`) AS a) + 1
       )

Again though, you're better off doing it in 2 queries. Reason being is the way AI works. If the last record is 20 and it gets deleted, the next entry will be 21 but the parent_id will be 20 because it will see the max(id) as 19.

Yes, you can. To get the next auto_increment value for your table you can do:

SELECT AUTO_INCREMENT 
FROM information_schema.TABLES 
WHERE table_name='table_name' 
AND table_schema='schema_name';

Don't use MAX , because if you remove the last row from table and calculate max, it will not give you the next auto_increment value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM