Check two fields no repeat in table when MySQL INSERT - mysql

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

Related

Ignore values on insert with ON DUPLICATE UPDATE

I have an Insert Statement like:
f"INSERT INTO `system_measurements`(`Global_irradiance_tilted_in_Wh_per_m2`, `a_id`, `subDate`) VALUES ('{temp}', '{temp_id}', '{i.date()}')"
And want it to ignore existing entries without checking the date everytime. So i thouhgt I could use
ON DUPLICATE KEY UPDATE a_id=a_id
But it still adds all values to the table.
I interpret your question as saying that a new row is inserted despite the on duplicate key.
In order for on duplicate key to work, you need a unique constraint or index. The update takes place when the query violates the unique constraint.
I am guessing that you want this on a_id, so be use you have something like:
alter table system_measurements add constraint unq_ system_measurements_a_id
unique (a_id);
INSERT IGNORE will do nothing other than discovering that it is a duplicate. "Duplicate" is checked via the PRIMARY KEY and any UNIQUE keys.
Simply stick IGNORE after INSERT in the SQL you have.

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.

Insert Ignore Into Mysql with a Primary Key

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)

How do I force an INSERT into a table with a unique key if it's already in the table?

I have a table:
CREATE TABLE Students (studentId TEXT PRIMARY KEY, name TEXT);
I want to insert records into the table, if I insert a student twice I want
the second insert to override(update) the first record.
INSERT INTO Students (StudentId, name) VALUES ('123', 'Jones');
INSERT INTO Students (StudentId, name) VALUES ('123', 'Jonas');
What's the best way of doing this?
Try REPLACE:
REPLACE INTO Students (StudentId, name) VALUES ('123', 'Jonas');
REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted.
You can also use the INSERT ... ON DUPLICATE KEY UPDATE syntax:
INSERT INTO Students
(StudentId, name)
VALUES ('123', 'Jones')
ON DUPLICATE KEY UPDATE
name = VALUES(name) ;
See this answer: insert-ignore-vs-insert-on-duplicate-key-update for differences between REPLACE, INSERT ... ON DUPLICATE KEY UPDATE and INSERT IGNORE.
But please, tell us that the studentId TEXT PRIMARY KEY is a typo. Do you really have a Primary Key that is TEXT datatype? The name (studentId) suggests that it could be a simple INT or INT AUTO_INCREMENT.
If you are using MySql - just use REPLACE instead of INSERT
I had a similar issue, but with a table that already had data in it, and no foreign keys, so my solution was very simple:
I added a new column called temp_id and made that a primary key, then afterwards deleted the old ID column, and then renamed the temp_id column to id.