MySQL Auto increment not incrementing - mysql

I've created a table with 3 columns: postID, userID, and comment.
I have the postID as the primary key, and I am trying to make this auto-increment every time I add a new row to the table.
INSERT INTO CommentTable (postID, userID, comment) VALUES (DEFAULT, "test", "test")
When I run this query, it will run OK once but then when I run it again I get "1062 - Duplicate entry '0' for key 'PRIMARY'".
How do I properly set up an auto-increment primary key?
Here is the table structure:
DROP TABLE IF EXISTS `CommentTable`;
CREATE TABLE `CommentTable` (
`postID` int(10) NOT NULL,
`userID` varchar(10) NOT NULL,
`comment` varchar(1000) DEFAULT NULL,
PRIMARY KEY (`commentID`)
)

No need to put the field postID
INSERT INTO CommentTable (userID, comment) VALUES ("test", "test")
Edit your table as:
CREATE TABLE `CommentTable` (
`postID` int(10) NOT NULL AUTO_INCREMENT,
`userID` varchar(10) NOT NULL,
`comment` varchar(1000) DEFAULT NULL,
PRIMARY KEY (`postID`)
)

Recently I had the same issue where Auto Increment was not saved. It failed every time I tried to save it. My problem was that I had a record where the value was 0 instead of 1, so I updated that record value to a non-zero value, then tried saving the Auto Increment, and it worked.
The zero(0) value in the Primary Index field was causing the ALTER tablename to fail. Once it worked, I put the value back to 0.

Related

How to use more than 1 auto-increment column in MySQL

I want to create a table name Users where I should have have columns User, cookieID, sessionID, Geo and then I want to first three columns to have some random unique value assigned automatically. I tried to make all three columns AUTO_INCREMENT with User column PRIMARY and 'cookieIDandsessionIDcolumnUNIQUE`. The SQL code is:
CREATE TABLE `users` ( `User` VARCHAR(20) NOT NULL AUTO_INCREMENT ,
`cookieID` INT(20) NULL DEFAULT NULL AUTO_INCREMENT ,
`sessionID` INT(20) NULL DEFAULT NULL AUTO_INCREMENT ,
`Geo` VARCHAR(30) NULL DEFAULT NULL ,
PRIMARY KEY (`User`), UNIQUE (`cookieID`), UNIQUE (`sessionID`), UNIQUE (`Geo`));
But, it did not work because only one column can be declared as AUTO_INCREMENT which must be PRIMARY.
What is the another approach to do this?
Since the auto-increment cannot be applied to multiple to rows and there no option for sequence in MySQL. You can use triggers for the unique update of the row with datetime.
Change to table creation to be of single auto-increment row.
CREATE TABLE `users` ( `User` VARCHAR(20) NOT NULL,
`cookieID` INT(20) NULL DEFAULT NULL,
`sessionID` INT(20) NULL DEFAULT NULL AUTO_INCREMENT ,
`Geo` VARCHAR(30) NULL DEFAULT NULL,
PRIMARY KEY (`User`), UNIQUE (`cookieID`), UNIQUE (`sessionID`), UNIQUE (`Geo`));
Create a trigger on the same table as below. You can set the unique values under the SET for as many column as you want.
CREATE DEFINER=`root`#`localhost` TRIGGER `users_BEFORE_INSERT` BEFORE INSERT ON `users` FOR EACH ROW BEGIN
SET
NEW.cookieID = (SELECT curdate()+curtime());
END
Now when you insert into the table as below.
insert into `users`(`User`) values("test");
You table looks like this.
User cookieID sessionID Geo
test 20315169 0 NULL
If the value which are auto incrementing, you wanna keep both values the same. Then copy the value of one column to another during insertion time of new value.

auto-increment value in update conflicts with internally generated values

I've been getting this error from an insert on duplicate update query in MYSQL randomly every now and then.
Any idea what's going on? I can't seem to reproduce the error consistently it occurs sometimes and then sometimes not.
Here is the query in question:
INSERT INTO friendships (u_id_1,u_id_2,status) VALUES (?,?,'active') ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id);
And the schema describing the table is:
DROP TABLE IF EXISTS `friendships`;
CREATE TABLE `friendships` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`u_id_1` int(11) NOT NULL,
`u_id_2` int(11) NOT NULL,
`status` enum('active','pending','rejected','blocked') DEFAULT 'pending' NOT NULL,
`initiatiator` enum('1','2','system') DEFAULT 'system' NOT NULL,
`terminator` enum('1','2','system') DEFAULT NULL,
`confirm_timestamp` timestamp DEFAULT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY (`u_id_1`,`u_id_2`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Your ON DUPLICATE KEY UPDATE statement isn't helping you at all here.
You are taking the LAST_INSERT_ID, which is the auto inc of the last successfully inserted row, and trying to update the duplicated row with that id. This will always cause a duplicate primary (you're trying to change the id of some row to match the id of the last thing you added)
If your goal is to either
Insert a new row, or
Update an existing row with 'active'
Then
INSERT INTO friendships (u_id_1,u_id_2,status)
VALUES ( ? , ? ,'active')
ON DUPLICATE KEY UPDATE
status = 'active'; -- I changed this
A separate consideration is to check the source for duplicates. I had a simple audit table
INSERT INTO table
field1, field2, ... , field3
ON DUPLICATE KEY UPDATE row_id=row_id;
where field1 is an INDEX but not UNIQUE with row_ID as INTEGER UNSIGNED AUTO_INCREMENT PRIMARY KEY.
Ran for years, but an unexpected duplicate row triggered this error.
Fixed by de-duping the source.
Possibly a trivial point to many readers here, but it cost me some head-scratching (followed by a facepalm).

Inserting into a view with an auto increment primary key?

I have a table horse and a view view_horse that selects every column from the horse table except the primary key (primary key is auto-increment integer) and then presents it to the user, I want to insert data into that views underlying table and naturally expect the primary key to be automatically generated. But I keep getting an SQL exception stating "field of view view_horse underlying doesn't have a default value" when I try to insert any data into it.
EDIT -
CREATE TABLE IF NOT EXISTS `TRC`.`horse` (
`horse_id` INT NOT NULL AUTO_INCREMENT,
`registered_name` VARCHAR(20) NOT NULL,
`stable_name` VARCHAR(20) NOT NULL,
`horse_birth_year` DATE NOT NULL,
`horse_height` DECIMAL(3,1) NOT NULL,
`horse_location` VARCHAR(50) NOT NULL DEFAULT 'TRC',
`arrival_date` DATE NOT NULL,
`passport_no` MEDIUMTEXT NULL,
`is_deceased` TINYINT(1) NOT NULL,
`arrival_weight` DECIMAL NOT NULL,
`horse_sex` VARCHAR(8) NOT NULL,
`microchip_no` VARCHAR(15) NULL,
`date_of_death` DATE NULL,
PRIMARY KEY (`horse_id`),
INDEX `fk_Horses_SexLookup1_idx` (`horse_sex` ASC),
CONSTRAINT `fk_Horses_SexLookup1`
FOREIGN KEY (`horse_sex`)
REFERENCES `TRC`.`lookup_sex` (`sex`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
USE `TRC`;
CREATE OR REPLACE VIEW `TRC`.`view_horse` AS SELECT
registered_name AS 'Registered Name',
stable_name AS 'Stable Name',
horse_birth_year AS 'Age',
horse_height AS 'Height',
arrival_weight AS 'Weight on Arrival',
horse_sex AS 'Sex',
horse_location AS 'Location',
arrival_date AS 'Date of Arrival',
passport_no AS 'Passport no.',
microchip_no AS 'Microchip no.',
is_deceased AS 'Alive?'
FROM `horse`;
If I insert into the view without specifying the columns it actually completes ok. But not when I give the columns as specified in the view.
You're not trying to INSERT into the actual VIEW are you? Insert into the TABLE, and SELECT from the VIEW.
Edit. Forget it; thanks for the correction Strawberry.
Here's a fiddle that illustrates inserting into the view: http://sqlfiddle.com/#!2/280aa6/1/0

alter table statment to insert duplicate into another table

I have a table in which there is a column name with SP varchar(10) NOT NULL. I want that column always to be unique so i created unique index on that column . My table schema as follows :
CREATE TABLE IF NOT EXISTS `tblspmaster` (
`CSN` bigint(20) NOT NULL AUTO_INCREMENT,
`SP` varchar(10) NOT NULL,
`FileImportedDate` date NOT NULL,
`AMZFileName` varchar(50) NOT NULL,
`CasperBatch` varchar(50) NOT NULL,
`BatchProcessedDate` date NOT NULL,
`ExpiryDate` date NOT NULL,
`Region` varchar(50) NOT NULL,
`FCCity` varchar(50) NOT NULL,
`VendorID` int(11) NOT NULL,
`LocationID` int(11) NOT NULL,
PRIMARY KEY (`CSN`),
UNIQUE KEY `SP` (`SP`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=10000000000 ;
Now i want that if anybody tries to insert duplicate record then that record should be inserted into a secondary table name tblDuplicate.
I have gone through this question MySQL - ignore insert error: duplicate entry but i am not sure that instead of
INSERT INTO tbl VALUES (1,200) ON DUPLICATE KEY UPDATE value=200;
can i insert duplicate row into another table ?
what changes needed to be done in main table scheme or index column ?
**Note : Data will be inserted by importing excel or csv files and excel files generally contains 500k to 800 k records but there will be only one single column **
I believe you want to use a trigger for this. Here is the MySQL reference chapter on triggers.
Use a before insert trigger. In the trigger, check if the row is a duplicate (maybe count(*) where key column value = value to be inserted). If the row is a duplicate, perform an insert into your secondary table.

MySQL Duplicate primary key on unexisting key

I've got a weird problem on a MySQL table. When trying to insert a new row, it says the primary key is duplicate. My primary key is auto incremental and is not set within my query (automatically set by MySQL).
The problem is I get a "Duplicate primary key" error on a key that doesn't even exists (I checked). I solved the problem increasing the current auto_increment value but I can't understand how it happened.
Any help would be great.
Edit
Table creation
CREATE TABLE `articles_mvt` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`ext_article_id` int(5) NOT NULL,
`date_mvt` date NOT NULL,
`qte` float(4,2) NOT NULL,
`in_out` enum('in','out') NOT NULL,
`ext_nateco_id` int(5) NOT NULL,
`ext_agent_id` int(5) NOT NULL COMMENT 'Demandeur',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1647 ;
Problematic query
INSERT INTO articles_mvt (
`ext_article_id`,
`date_mvt`,
`qte`,
`in_out`,
`ext_nateco_id`,
`ext_agent_id`
)
VALUES (
'".$_POST["numArticle"]."',
'".dateSql($_POST["date_mvt"])."',
".$_POST["qte_entier"].".".$_POST["qte_virgule"].",
'".$_POST["in_out"]."',
".$_POST["numNateco"].",
".$_POST["demandeur"]."
)
FYI variables are sanitized earlier in the code ;)
Well i think at that time you did not check auto Inc flag on primary key. So when you try to enter than value 0 is insert in the primary key and for second entry it gives error. like that
ID Value
0 A ok it not give error
0 ff it gives error..
Or you may try to insert a row whose ID is already exist like
ID Value
11 A ok it not give error
11 ff it gives error..