When inserting data, Insert statement conflicted with the Foreign Key constraint - mysql

I have a table called Book_details, which has a primary key as Bid and now this BID is also a foreign key for other two table in the same database (I.e slend_details, Book_inventory)
When I insert data into inventory_details table, I'm getting the following error:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK__book_invent__Bid__1367E606". The conflict occurred in database "library_management", table "dbo.Book_details", column 'Bid'.
The statement has been terminated.
This is the insert statement I used:
insert into Book_inventory (Bid, present) values (001,1)
This is the create statement I used for my book_inventory table:
create table book_inventory (
Bid varchar(50) Not null Foreign Key references Book_details(Bid),
present bit Not null*
)
I have even checked the values i.e the data I am trying to enter in book_inventory table is present in the Book_details table. Still I get the error. Can someone help me out?

Your insert;
insert into Book_inventory (Bid,present) values (001,1)
inserts Bid as an integer, which most likely means that it simplifies the value to 1 which does not exist as a Bid.
Quoting the value and inserting it as an actual string should work;
insert into Book_inventory (Bid,present) values ('001',1)

column Bid is varchar and you are using it as integer. try this query
insert into Book_inventory (Bid, present) values ('001',1)

Related

Error: Duplicate entry '1' for key 'students.PRIMARY' Error Code: ER_DUP_ENTRY

CREATE TABLE IF NOT EXISTS students (
student_id INT,
name VARCHAR(24),
major VARCHAR(24),
PRIMARY KEY(student_id)
);
SELECT * FROM student;
INSERT INTO students VALUES(1,'Jack','Biology');
You're specifying the primary key (student_id) and from the error it already exists. You have a few options:
Don't specify the primary key. It should be set to autoincrement anyway, assuming that this is the primary table that students are entered into, and from the name of the table (students) it seems like it is. Then the query will be:
INSERT INTO students VALUES('Jack','Biology');
and then the table will autoincrement the primary key to the next pointer.
Use INSERT IGNORE. This will silently fail if you try to insert a student ID that already exists (or on any query that violates unique keys).
INSERT IGNORE INTO students VALUES(1, 'Jack','Biology');
This will not cause table changes, but it will also not cause an error that interrupts the script, and it will insert any rows that don't fail, say if you had multiple values inserted. The plain INSERT will fail for the entire list, not just the erroneous value.
Use ON DUPLICATE KEY UPDATE. This will update a list of values if it encounters a duplicate key.
INSERT INTO students VALUES(1, 'Jack','Biology')
ON DUPLICATE KEY UPDATE name = values(name), major = values(major);
In this case, you will change the values in the table that match the key. In this case, whichever student is student_id 1 will have its name and major updated to the supplied values. For instance, let's say that Jack changed his major to Chemistry. This would update student_id 1 to Jack, Chemistry and reflect his new major.
Use REPLACE INTO. I avoid this one. It is similar to ON DUPLICATE KEY UPDATE, but it removes the old entry and replaces it with a new one with a new ID. This can cause you problems with foreign keys, and also if you have a small primary key and you constantly replace into it, you can end up with a primary id that's bigger than the limits you set.
Well, your student_id is primary key, clearly that table is already exist with some data with student_id=1 hence you cannot insert another row with the same primary key value.

Sql Statement: Insert On Key Update is not working as expected when primary key is not specified in the fields to insert

Hello I am using the "INSERT ON DUPLICATE KEY UPDATE" sql statement to update my database.
All was working fine since I always inserted an unique id like this:
INSERT INTO devices(uniqueId,name)
VALUES (4,'Printer')
ON DUPLICATE KEY UPDATE name = 'Central Printer';
But for now, I need to insert elements but I don't insert a unique id, I only insert or update the values like this:
INSERT INTO table (a,b,c,d,e,f,g)
VALUES (2,3,4,5,6,7,8)
ON DUPLICATE KEY
UPDATE a=a, b=b, c=c, d=d, e=e, f=f, g=g;
Have to say that an autoincrement primary key is generated always that I insert a row.
My problem is that now the inserted rows are duplicated since I don't insert the primary key or unique id explicitly within the sql statement.
What I am supposed to do?
For example, maybe I need to insert the primary key explicitly? I would like to work with this primary autoincremented key.
For recommendation from Gordon I am adding a sample case the you can see in the next image
Rows Output
In this case I add the first three rows, and then I try to update the three first rows again with different information.... Ok I am seeing the error... There is no key to compare to...... :$
Thanks for your answers,
If you want to prevent columns from being duplicated, then create a unique index or constraint on them. For instance:
create unique index unq_table_7 on table(a, b, c, d, e, f, g);
This will guarantee that the 7 columns -- in combination -- are unique.

if reforeign key is in itself

if the foreign key is in itself table, how to handle the first insertion problem.
/*外键是自己本身该如何处理插入问题*/
create table if not exists Course(
Cno varchar(10) primary key,
Cname varchar(100) not null,
Cpno varchar(10),
Ccredit tinyint,
foreign key (cpno) references course(cno)
);
/* the under sql will across error */
insert into Course(cno,cname,cpno,ccredit) value("1","数据库","5",4);
insert into Course(cno,cname,cpno,ccredit) value("2","数学",null,2);
insert into Course(cno,cname,cpno,ccredit) value("3","信息系统","1",4);
insert into Course(cno,cname,cpno,ccredit) value("4","操作系统","6",3);
insert into Course(cno,cname,cpno,ccredit) value("5","数据结构","7",4);
insert into Course(cno,cname,cpno,ccredit) value("6","数据处理",null,2);
insert into Course(cno,cname,cpno,ccredit) value("7","PASCAL语言","6",4);
enter image description here
how can I initialize the table course with Mysql?
Your first INSERT is this:
insert into Course(cno,cname,cpno,ccredit) value("1","数据库","5",4);
This attempts to create a row with value 5 in the column defined as the foreign key (FK), but without ensuring that a row with a cno value of 5 already exists. The FK constraint therefore refuses the insert.
You can fix this in one of three ways.
First, insert your rows in an order that insures the cno values exist before you use them by referring to them in cpno. I think this will be:
2, 6, 7, 5, 1, 3, 4
where you work out the order with a graph-traversal algorithm starting with root rows (rows with null cpno values).
Second, try turning off foreign key checking by giving this command SET FOREIGN_KEY_CHECKS=0; before your inserts. Give this command after your inserts to re-enable checking. SET FOREIGN_KEY_CHECKS=1;
Third, drop the foreign key constraint from the table before doing your inserts. Then add it back when you're done.
The second two methods generally apply only to bulk insertion operations you do on a quiet system. You probably don't want to disable foreign key checking in production, because it has value for data integrity assurance.
Read this. How to temporarily disable a foreign key constraint in MySQL?

Can I use INSERT INTO ... On DUPLICATE KEY without by using auto_increment value?

I am trying to write a query to check if a record exists (based on couple of clause and not unique identifier) if such a search return records then I need to update all the found records if nothing found then I need to INSERT a record. Note that I can't use IF EXISTS because I am trying to make a query for a client side script and not a server side. So I came a cross the idea of INSERT INTO .... ON DUPLICATE KEY
Can I do this without knowing the row key identifier? So if I find a record where accountid = 17 and name = 'Mike' then update it to make the name 'Mike A' if there is no record with these 2 clause then insert a record.
This is an attempt that is giving me a syntax error
INSERT INTO test (name, accountid) VALUES ('Mike', 17)
ON DUPLICATE KEY
UPDATE test SET name='Mike A' WHERE name ='Mike' AND accountid = 17
Can this method handle what I am trying to do? If yes then can you please correct my syntax?
Thank you
The only way you can get this to work is if you have a primary key or unique constraint on the fields. From the documentation:
If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that
would cause a duplicate value in a UNIQUE index or PRIMARY KEY, an
UPDATE of the old row is performed. For example, if column a is
declared as UNIQUE and contains the value 1, the following two
statements have identical effect:
create table test (name varchar(100), accountid int);
insert into test values ('Mike', 17);
alter table test add unique (name, accountid);
insert int test (name, accountid) values ('Mike', 17)
on duplicate key update name='Mike A';
SQL Fiddle Demo
Without the unique key, it will insert a duplicate record.

Check two fields no repeat in table when MySQL INSERT

I have following table:
table (id,
longitude,
latitude,
longlat,
address,
description,
kind,
synonym,
primary key(id)
);
I need to check that fields longlat and description in inserting row are unique and there are no rows with same combination of longlat and description it the table, inserted before it.
How should I modify my query?
"INSERT INTO yandex_social_objects (longitude,latitude,longlat,address,description,kind,synonym) VALUES (val_1),(val_2),(val_3)...(val_n)"
Add a UNIQUE constraint on the combination so this never happens:
ALTER TABLE yandex_social_objects
ADD CONSTRAINT longlat_description_UQ
UNIQUE (longlat, description) ;
After that, all your Inserts into the table will check this combination for uniqueness and either succeed or fail.
You can use INSERT IGNORE or INSERT ... ON DUPLICATE KEY UPDATE ... for different behaviour on unique key collisions. Check this answer for differences: INSERT IGNORE vs INSERT … ON DUPLICATE KEY UPDATE