Insert Ignore Into Mysql with a Primary Key - mysql

I am trying to use INSERT IGNORE INTO to add a row to a table if it doesn't already exist.
Here is the statement as it stands right now:
INSERT IGNORE INTO my_table (integer, date) VALUES (11111, CURDATE())
However, since I have an auto-incrementing primary key on the table (that is not part of the insert of course), it always does the insert. Is there a way to disregard the primary key so that if the integer and date are already in the table it will not insert another row with them?

Put a UNIQUE key on the integer and the date, or the combination of the two - whichever fits your needs. That will prevent INSERT IGNORE from inserting values that violate the UNIQUE index.
For example if you want to make the combination of the two unique:
alter table my_table add unique index(integer, date)

Related

Unique key constraint without order of columns

I have a table
drug_interaction(drug1_id ,drug2_id )
I want to know if it is possible to have unique pairs of drug1_id and drug2_id without taking into consideration the order of the values. For example if (1,2) already exists in the table
then inserting (2,1) should not be allowed.
This is hard to do in MySQL. In many databases, you can ensure that the drugs are in order using a check constraint:
check (drug1_id < drug2_Id)
However, MySQL does not actually enforce these constraints.
The only way you can enforce this is using a trigger on the table.
One way to do it would be to create two computed columns that store the smallest and greatest drug_ids on each record, and the put a unique constraint on them.
Consider:
create table drug_interaction(
drug1_id int ,
drug2_id int,
drug_least int as (least(drug1_id, drug2_id)) stored,
drug_greatest int as (greatest(drug1_id, drug2_id)) stored,
unique key unique_drugs (drug_least, drug_greatest)
)
Demo on DB Fiddle:
insert into drug_interaction(drug1_id, drug2_id) values(1, 2)
-- ok
insert into drug_interaction(drug1_id, drug2_id) values(2, 1)
-- error: Duplicate entry '1-2' for key 'unique_drugs'

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.

MySQL "Insert ... On Duplicate Key" with more than one unique key

I've been reading up on how to use MySQL insert on duplicate key to see if it will allow me to avoid Selecting a row, checking if it exists, and then either inserting or updating. As I've read the documentation however, there is one area that confuses me. This is what the documentation says:
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
The thing is, I don't want to know if this will work for my problem, because the 'condition' I have for not inserting a new one is the existence of a row that has two columns equal to a certain value, not necessarily that the primary key is the same. Right now the syntax I'm imagining is this, but I don't know if it will always insert instead of replace:
INSERT INTO attendance (event_id, user_id, status) VALUES(some_event_number, some_user_id, some_status) ON DUPLICATE KEY UPDATE status=1
The thing is, event_id and user_id aren't primary keys, but if a row in the table 'attendance' already has those columns with those values, I just want to update it. Otherwise I would like to insert it. Is this even possible with ON DUPLICATE? If not, what other method might I use?
The quote includes "a duplicate value in a UNIQUE index". So, your values do not need to be the primary key:
create unique index attendance_eventid_userid on attendance(event_id, user_id);
Presumably, you want to update the existing record because you don't want duplicates. If you want duplicates sometimes, but not for this particular insert, then you will need another method.
If I were you, I would make a primary key out of event_id and user_id. That will make this extremely easy with ON DUPLICATE.
SQLFiddle
create table attendance (
event_id int,
user_id int,
status varchar(100),
primary key(event_id, user_id)
);
Then with ease:
insert into attendance (event_id, user_id, status) values(some_event_number, some_user_id, some_status)
on duplicate key
update status = values(status);
Maybe you can try to write a trigger that checks if the pair (event_id, user_id) exists in the table before inserting, and if it exists just update it.
To the broader question of "Will INSERT ... ON DUPLICATE respect a UK even if the PK changes", the answer is yes: SQLFiddle
In this SQLFiddle I insert a new record, with a new PK id, but its values would violate the UK. It performs the ON DUPLICATE and the original PK id is preserved, but the non-UK ON DUPLICATE KEY UPDATE value changes.

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

MySQL INSERT only if two fields don't match

I have 6 fields with the primary as ID and is set to auto_increment. I want to INSERT a new row if DATE and FROM do not match. I was thinking of REPLACE INTO or ON DUPLICATE KEY UPDATE but from what I know I have to have one of them as my Primary? I don't care how its done I just need some help with a query that would work.
ID
DATE
STORE
TOTAL
NPS
FROM
What you need is a unique index composed of both the DATE and FROM fields.
ALTER TABLE table ADD UNIQUE INDEX(DATE, FROM);
Then you can use this type of query:
INSERT IGNORE INTO table (columns) VALUES (...)
The IGNORE statement will skip any INSERT that would otherwise cause a duplicate key error.