MySQL doesn't support multiple auto increment columns.
CREATE TABLE IF NOT EXISTS `parts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`order` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Is there another solution to make the value of column order
increase automatically when I insert a new record?
MySQL server already provides two auto increment variables: auto_increment_increment and auto_increment_offset, which can be used to generate different auto increment values on each member.
You can't have two auto-increment columns.
Here's the syntax of ALTER TABLE statement, ALTER TABLE table_name MODIFY column_name INT NOT NULL AUTO_INCREMENT PRIMARY KEY; In the above statement, you need to specify the table_name and column_name. Here's the SQL statement to add AUTO INCREMENT constraint to id column.
In MySQL, the syntax to reset the AUTO_INCREMENT column using the ALTER TABLE statement is: ALTER TABLE table_name AUTO_INCREMENT = value; table_name. The name of the table whose AUTO_INCREMENT column you wish to reset.
You can do it from within your application by issuing another query that increases order
or you can create a trigger that does that for you. Whatever you do, for the sake of sanity of programming world - don't use reserved words for column names such as order
:)
Why do you want 2 fields to be auto incremented - they will have the same values anyway so you can just use ID.
If you want to have your invoices/orders to have sequential numbers then you should keep that numbering in separate table and haves separate logic to update those numbers.
Based on your original table:
CREATE TABLE IF NOT EXISTS `parts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`order` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
How about this single insert query:
INSERT INTO `parts` (`name`, `order`)
SELECT 'name of new part', IFNULL(MAX(`order`), 0) + 1 FROM parts;
If the claim is true that this is not a safe query, one can simply introduce table locking as follows:
LOCK TABLES `parts` AS t1 WRITE, `parts` WRITE;
INSERT INTO `parts` (`name`, `order`)
SELECT 'name of new part', IFNULL(MAX(`order`), 0) + 1 FROM `parts` AS t1;
UNLOCK TABLES;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With