Issue in insert query mysql error#1364 - mysql

my query is
INSERT INTO `session_card` (`flags`, `history`, `showtime`, `session_id`, `card_id`, `card_mode`) VALUES ('', 'ö', '12', 9410, '256', 'rw')
and the table structure is
DROP TABLE IF EXISTS `session_card`;
CREATE TABLE IF NOT EXISTS `session_card` (
`id` int(11) NOT NULL,
`session_id` int(11) DEFAULT NULL,
`card_id` int(100) DEFAULT NULL,
`history` varchar(1000) DEFAULT NULL,
`flags` varchar(255) NOT NULL DEFAULT '',
`showtime` varchar(2000) DEFAULT NULL,
`card_mode` varchar(10) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`),
UNIQUE KEY `session_card_unique_key` (`session_id`,`card_id`,`card_mode`),
KEY `fk` (`session_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
COMMIT;
Now I dont understand what is the issue here also my phpmyadmin show only error code it doesnt give me the error expatiation. Any one can help me with this.

You need to have AUTO_INCREMENT on your id column, or you will need to pass a unique id manually every time you insert a row.
Change:
CREATE TABLE IF NOT EXISTS `session_card` (
`id` int(11) NOT NULL,
to:
CREATE TABLE IF NOT EXISTS `session_card` (
`id` int(11) NOT NULL AUTO_INCREMENT,
I would also suggest adding UNSIGNED as well since id's usually don't contain negative values.

In your schema, you have given id` int(11) NOT NULL but while inserting data you are not passing any value for id. as id is a not null constraint you should pass the value for id.

Modify you ID column to AUTO_INCREMENT flag
ALTER TABLE session_card MODIFY id int NOT NULL AUTO_INCREMENT
Make sure you table is empty before executing the above sql

If you are not setting a primary key id to Auto Increment then provide a value while inserting.
Otherwise, set it to AutoIncrement. This is better way to assigning a value.
INSERT INTO `session_card`
(`id`,`flags`, `history`, `showtime`, `session_id`, `card_id`, `card_mode`) VALUES
('1','', 'ö', '12', 9410, '256', 'rw')

Might be it's because of strick mode
Disable it:
SET sql_mode = '';
After this try insert query.

please make id key is auto increment
like following.
ALTER TABLE session_card MODIFY id int NOT NULL AUTO_INCREMENT
Otherwise add manually id at insertion time. like following.
INSERT INTO session_card
(id,flags, history, showtime, session_id, card_id, card_mode) VALUES
('1','', 'ö', '12', 9410, '256', 'rw')

Related

Can you insert ignore into table if certain fields are duplicate?

I am trying to insert into a MySQL table, but I came across a problem that I can't seem to solve. The problem is that I want to add a record into the table if certain fields are duplicate, but not all.
To make my problem more clear this is the table:
When I want to do an insert into this table, I want to insert ignore only if userid and status and url are duplicate. If one of those 3 are unique the record can be added into the table.
What I have tried:
INSERT IGNORE INTO mydb.mytable (unique_screen_id, userid, url, status)
VALUES ('1234', 1, 'something.com', 'active');
This does not give the desired result since unique_screen_id will never be duplicate and thus the statement will insert the record. I can't remove the unique_screen_id out of the query since it also needs to be added into the table
Which query can I use so that if I insert the record above, it will check if userid and status and url are duplicate, and if they are ignore the statement (and otherwise insert the statement)?
Edit:
As requested my create table query:
CREATE TABLE `screens` (
`id` int NOT NULL AUTO_INCREMENT,
`unique_screen_id` varchar(20) DEFAULT NULL,
`userid` int DEFAULT NULL,
`status` enum('active','finished') DEFAULT 'active',
`url` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
I am not sure what your create table statement is like but you can add UNIQUE key:
UNIQUE (userid ,url, status)
Here is a demo
So first you create table like this(without UNIQUE KEY):
CREATE TABLE `screens2` (
`id` int NOT NULL AUTO_INCREMENT,
`unique_screen_id` varchar(20) DEFAULT NULL,
`userid` int DEFAULT NULL,
`status` enum('active','finished') DEFAULT 'active',
`url` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
then if you add this line
INSERT IGNORE INTO screens2 ( unique_screen_id, userid, url, status)
VALUES ( 1, '1', 'something.com', 'active');
and then this line
INSERT IGNORE INTO screens2 ( unique_screen_id, userid, url, status)
VALUES ( 1, '1', 'something.com', 'finished');
and then this line
INSERT IGNORE INTO screens2 ( unique_screen_id, userid, url, status)
VALUES ( 2, '1', 'something.com', 'finished');
all 3 lines will be inserted...
If you create your table like this:
CREATE TABLE `screens` (
`id` int NOT NULL AUTO_INCREMENT,
`unique_screen_id` varchar(20) DEFAULT NULL,
`userid` int DEFAULT NULL,
`status` enum('active','finished') DEFAULT 'active',
`url` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`),
unique(userid, url, status)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
Only two of the lines will be inserted and one will be ignored.
P.S. If you add UNIQUE key you will no IGNORE keyword with your insert statements.
As the user VBoka suggested the following demo displays the answer!
I needed to use a combination of the insert ignore statement and the Unique keyword!
Thanks!
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=5d19c458568ef9204c257b7ef6096eab

How to avoid duplicate key error in mysql

I have a problem to get a next sequence id in my code. Though it was a legacy code i have to follow the same. Let me explain the logic which was followed.
CREATE TABLE `emp_seq` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=1234 DEFAULT CHARSET=utf8
Above table used to get the next sequence id for the below table. and also emp_seq table will have only one entry for the id.
CREATE TABLE `emp_info` (
`id` BIGINT(8) UNSIGNED NOT NULL,
`name` VARCHAR(128) DEFAULT '',
`active` TINYINT(2) DEFAULT '1',
`level` MEDIUMINT(8) DEFAULT '100',
PRIMARY KEY (`id`),
KEY `level` (`level`)
) ENGINE=INNODB DEFAULT CHARSET=utf8 COMMENT='employee information'
so whenever we trying to insert a new record to emp_info table, we are getting next sequence id from the table emp_seq by using below queries.
INSERT INTO emp_seq () VALUES ();
DELETE FROM emp_seq WHERE id < LAST_INSERT_ID;
Now the problem is, some times because of multiple asynchronous calls in the application, the same increment id has been shared to multiple records and trying to insert in the emp_info table and we are getting below error
"code":"ER_DUP_ENTRY","errno":1062,"sqlMessage":"Duplicate entry 1234 for key
Kindly help me how to resolve the issue.

Is it possible to make a batch insert/update if the uniqueness of the record is a bundle of two fields?

I have the following table structure (example)
CREATE TABLE `Test` (
`id` int(11) NOT NULL,
`order_id` int(11) NOT NULL,
`position_id` int(11) NOT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`price` decimal(10,2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
ALTER TABLE `Test` ADD PRIMARY KEY (`id`);
ALTER TABLE `Test` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
This table contains data that is constantly in need of updating. There is also new data that needs to be entered. Since there is a lot of data, it will take quite a long time to check each record to make it insert or update.
After studying the question, I realized that I need to use batch insert/update with:
INSERT on DUPLICATE KEY UPDATE
But the documentation says that the fields must have a unique index. But I don't have any unique fields, I can't use the ID field. The uniqueness of the record can only be in a combination of two fields order_id and position_id.
Is it possible to make a batch insert/update if the uniqueness of the record is a bundle of two fields?
You need a composite primary-key. You also don't need your AUTO_INCREMENT id column, so you can drop it.
Like so:
CREATE TABLE `Test` (
`order_id` int NOT NULL,
`position_id` int NOT NULL,
`name` varchar(255) NOT NULL COLLATE utf8mb4_unicode_ci,
`price` decimal(10,2) NOT NULL,
CONSTRAINT PK_Test PRIMARY KEY ( `order_id`, `position_id` )
) ENGINE=InnoDB
Then you can use INSERT ON DUPLICATE KEY UPDATE.

Can I add a Unique key on table creation in SQL?

I am trying to translate a collection of MySQL functions to SQL, and I'm having issues with a UNIQUE KEY issue:
-- -----------------------------------------------------
-- Table testform
-- -----------------------------------------------------
CREATE TABLE `testform` (
`FormId` INT(11) NOT NULL AUTO_INCREMENT,
`TTId` INT(11) NULL DEFAULT NULL,
`TestName` VARCHAR(100) NULL,
PRIMARY KEY (`FormId`),
UNIQUE KEY `TF_Composite` (`TTId`, `TestName`));
When I try and test this in SQLFiddle, it's giving me the error
Incorrect syntax near the keyword 'KEY'.
I have tried searching for this, but so far all I have come up with is "Unique Constraints". Is there a difference between a "Key" and a "Constraint" in SQL? And if so, how can I add this in the table creation statement?
Your syntax is all messed up. Please look at books on-line (MSDN).
https://msdn.microsoft.com/en-us/library/ms174979.aspx
The sample code below create a table in tempdb. This table automatically gets destroyed when the service is restarted.
-- Just a example, throw away after reboot
USE [tempdb]
GO
-- Create the table
CREATE TABLE DBO.TESTFORM
(
FORM_ID INT IDENTITY(1, 1) NOT NULL ,
TT_ID INT NULL,
TEST_NAME VARCHAR(100) NULL,
CONSTRAINT PK_FORM_ID PRIMARY KEY (FORM_ID),
CONSTRAINT UN_COMPOSIT UNIQUE (TT_ID, TEST_NAME)
);
-- Seventies Band
INSERT INTO TEMPDB.DBO.TESTFORM VALUES (1, 'John');
INSERT INTO TEMPDB.DBO.TESTFORM VALUES (2, 'Paul');
INSERT INTO TEMPDB.DBO.TESTFORM VALUES (3, 'Mary');
GO
-- Show data
SELECT * FROM TEMPDB.DBO.TESTFORM
GO
The image below shows the data in this table.
Try This.
CREATE TABLE testform (
FormId INT(11) NOT NULL AUTO_INCREMENT,
TTId INT(11) NULL DEFAULT NULL,
TestName VARCHAR(100) NULL,
PRIMARY KEY (FormId),
CONSTRAINT TF_Composite UNIQUE (TTId,TestName));
More Details..
For Better Understanding about Primary and Unique you can refer below page.
Primary and Unique Key Creation
For MySQL Database
CREATE TABLE `phone` (
`id` MEDIUMINT(8) UNSIGNED NOT NULL AUTO_INCREMENT,
`country` DECIMAL(5,0) UNSIGNED NOT NULL,
`area` DECIMAL(5,0) UNSIGNED NOT NULL,
`number` DECIMAL(8,0) UNSIGNED NOT NULL,
`extension` DECIMAL(5,0) UNSIGNED DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `ix_phone` (`country`, `area`, `number`, `extension`),
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
For alter Table :
ALTER TABLEphone
ADD UNIQUE INDEXix_phone(country,area,number,extension);

How can I change ID to Auto Incremental after making relationships in MySQL

I am trying to study MySQL and JDBC so I created a database. I didn't know that I had to make my ID's auto incremental. So when I was trying to create a function for inserting data in database in JDBC, I was told that the ID's should be auto incremental and I shouldn't add them manually. As I already have added all the data and structured the database(making relationships, adding foreign and primary keys) I can't make my ID's autoIncremental, because they are foreign keys in different tables. I don't wan't to delete data from my database and start from beginning. What are my options other than giving ID's manually in JDBC?
Can I somehow change my ID's and make them Auto Incrimental?
I think that me having foreign keys in other tables is the problem. But I don't want to delete them as I have put lot's of data in my database.
This is the MySQL workbench. I tried to add. AutoIncremental from here.
The MySQL workbench applies this SQL script:
ALTER TABLE `university`.`student`
CHANGE COLUMN `StudentID` `StudentID` INT(11) NOT NULL AUTO_INCREMENT ;
And Finally I get this Error:
ERROR 1833: Cannot change column 'StudentID': used in a foreign key constraint 'studentsection_ibfk_1' of table 'university.studentsection'
SQL Statement:
ALTER TABLE `university`.`student`
CHANGE COLUMN `StudentID` `StudentID` INT(11) NOT NULL AUTO_INCREMENT
ERROR: Error when running failback script. Details follow.
ERROR 1046: No database selected
SQL Statement:
CREATE TABLE `student` (
`StudentID` int(11) NOT NULL DEFAULT '0',
`LastName` varchar(255) COLLATE latin1_general_ci DEFAULT NULL,
`FirstName` varchar(255) COLLATE latin1_general_ci DEFAULT NULL,
`StudentGPA` float DEFAULT NULL,
`Major` varchar(255) COLLATE latin1_general_ci DEFAULT NULL,
`MajorID` int(11) DEFAULT NULL,
PRIMARY KEY (`StudentID`),
KEY `MajorID` (`MajorID`),
CONSTRAINT `student_ibfk_1` FOREIGN KEY (`MajorID`) REFERENCES `major` (`MajorID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci
P.S. Im working with MySQL Workbench, PHPMyAdmin and Eclipse for JDBC.
You only have to make the id column a key and change the property to be autoincrement:
CREATE TABLE `test` (
`id` INT NULL,
`value` INT NULL
)
COLLATE='latin1_swedish_ci'
ENGINE=MyISAM;
INSERT INTO `test` (`id`, `value`) VALUES (1, 23);
INSERT INTO `test` (`id`, `value`) VALUES (5, 42);
With the above code, I simulate a populated table with your values. Then, this is the code you're interested:
ALTER TABLE `test`
CHANGE COLUMN `id` `id` INT(11) NULL AUTO_INCREMENT FIRST,
ADD INDEX `Índice 1` (`id`);
After that, you'll have an autoincrement field, so you won't need to add the id again:
INSERT INTO `test` (`value`) VALUES (23);