Insert a row only if doesn't exist without getting its id - mysql

I followed this tutorial with 'INSERT IGNORE' first and 'INSERT ... ON DUPLICATE KEY UPDATE' then. But it doesn't work.
I'm using NodeJS to get some data from an API, and store these data into a mySQL database. Before storing data, I want to know if this row already exists.
The ID is AUTO_INCREMENT and I d'ont know this one. Instead of using async/await or promises in NodeJS, I wanted to treat this point with mySQL without knowing the ID.
I tried this one but it adds a new row with a new ID instead of another row already exists:
INSERT INTO test (nom, date, heure) VALUES ('123456', '2018-08-23', '10:45:00') ON DUPLICATE KEY UPDATE nom='123456', date='2018-08-23', heure='10:45:00';
After that, I tested this one, same result:
INSERT IGNORE INTO test (nom, date, heure) VALUES ('123456', '2018-08-23', '10:45:00')
Thanks for your help!

Set a unique index for the 3 columns:
ALTER TABLE test ADD UNIQUE un_index(nom, date, heure);
Then execute:
INSERT IGNORE INTO test (nom, date, heure) VALUES ('123456', '2018-08-23', '10:45:00');
If the 3 values already exist, the row will not be inserted.

Related

Auto generate Primary Key if not present in MySQL INSERT Query

I created a table in MySql
CREATE TABLE newuser(id VARCHAR(10) PRIMARY KEY,sname VARCHAR(20));
When I INSERT record it works fine
INSERT INTO newuser VALUE('abc123','monika');
But sometimes I don't want to supply id in the INSERT query and sometimes I want to supply. In case I don't supply id MySql automatically generate one.
What can I do to get both below query works?
INSERT INTO newuser VALUE('abc123','monika');
INSERT INTO newuser VALUE('nikita');
'I don't understood ANYTHING' - very new then.
Firstly second insert statement is invalid please review https://dev.mysql.com/doc/refman/8.0/en/insert.html -
'If you do not specify a list of column names for INSERT ... VALUES or INSERT ... SELECT, values for every column in the table must be provided by the VALUES list, SELECT statement, or TABLE statement.'
Secondly uuid is a function in which 'A UUID is designed as a number that is globally unique in space and time.' https://dev.mysql.com/doc/refman/8.0/en/insert.html
You can easily select uuid() to see what it produces.
You will need to increase the id size
If you wish to use it in an insert
insert into users values (uuid(),<sname>);

MYSQL innerjoin insert Multiple tables

Hello i'll give you guys an example of the database tables that are being a pain so i got 3 conected tables yeah trying to make a list into a database anyway i'm having trouble writing a insert query for it
vogelsoort
id|naam|idhooftoonder|
now idhoofdtoonder references to the id a connection table to sort of translate a list to a mysql database (the logic of the table will be added underneath)
hoofdtoonder
|pkey|Id|idondersoorten
now idhoofdtoonder references to a the following table its id
ondersoort
id|naam
I'm sorry for asking this also i'm not experienced enough yet in mysql
edit: the question is since i've tried with a simple insert query it overwrote existing data that i'm looking for help with an insert without overwriting existing id's and connections since (idhootoonder references to hooftonder(id) and hooftoonder idontersoorten references to ondersoort(id) but not all data in ondersoort is connected to the same vogelsoort and i need an insert query that doesn't overide existing connections
You need 3 insert-statements, one for each table.
You may use TRANSACTION to do it safely.
You need to use LAST_INSERT_ID() function (your PK fields must been auto_increment for this), docs: http://dev.mysql.com/doc/refman/5.7/en/information-functions.html#function_last-insert-id
START TRANSACTION;
INSERT INTO ondersoort (id, naam) VALUES (NULL, 'data');
INSERT INTO hoofdtoonder (pkey, Id, idondersoorten) VALUES (NULL, NULL, LAST_INSERT_ID());
INSERT INTO vogelsoort (id, naam, idhooftoonder) VALUES (NULL, 'data', LAST_INSERT_ID());
COMMIT;

MySQL replace into and get last insert ID

In MySQL, will a REPLACE INTO query work with the LAST_INSERT_ID function?
Essentially, I have to insert into one table, only where it doesn't exist, but then either way insert into the second table with a foreign key constraint of the first table.
So ie.
REPLACE INTO TABLE1(NAME) VALUES('unique');
SET #table1_id = LAST_INSERT_ID();
INSERT INTO TABLE2(TABLE1_ID, VALUE) VALUES(#table1_id, 'Test Value');
Will that function as intended on both an insert and an update?
Yes, REPLACE INTO query affects the result of LAST_INSERT_ID() function.
Documentation states:
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.
That means if INSERT affects LAST_INSERT_ID() then REPLACE should do it too.
I have tested it with MySQL 8.

IF NOT EXISTS then INSERT

I'm trying to add a value to a table but not without checking if the value already exists. This is what I have so far:
IF NOT EXISTS (
SELECT series.seriesName
FROM series
WHERE series.seriesName='Avengers'
)
BEGIN
INSERT INTO series (seriesName) VALUES 'Avengers'
END;
Database is a MySQL db on Ubuntu
You can use IGNORE keyword here.
It could look like:
INSERT IGNORE INTO series (seriesName) VALUES 'Avengers'
The important thing is to create a unique key on seriesName field as it seems that you want it to be unique.
INSERT IGNORE doesn't make the insert when key value already exists.
If you would like to be able to get id (primary key value) for row that wasn't inserted (already existed), you can do the following trick:
INSERT IGNORE INTO series (seriesName) VALUES 'Avengers'
ON DUPLICATE KEY UPDATE seriesID= LAST_INSERT_ID(seriesID)
Then you will be able to get the ID with LAST_INSERT_ID() function no matter if the row was inserted or not.

mysql - after insert ignore get primary key

i am running a query in mysql insert ignore into........ using Python
after running the query I want to know the primary key of the row. I know there is the query
SELECT LAST_INSERT_ID();
but i'm not sure if it will work with insert ignore
what is the best way to do this?
The documentation for LAST_INSERT_ID() says:
If you use INSERT IGNORE and the row is ignored, the AUTO_INCREMENT counter is not incremented and LAST_INSERT_ID() returns 0, which reflects that no row was inserted.
Knowing this, you can make this a multi-step process:
INSERT IGNORE
if LAST_INSERT_ID(), then done (new row was inserted)
else SELECT your_primary key FROM yourtable WHERE (your inserted data's UNIQUE constraints)
Example with U.S. states:
id | abbrev | other_data
1 | AL | ...
2 | AK |
UNIQUE KEY abbr (abbrev)
Now, inserting a new row:
INSERT IGNORE INTO `states` (`abbrev`,`other_data`) VALUES ('AZ','foo bar');
> OK
SELECT LAST_INSERT_ID();
> "3"
// we have the ID, we're done
Inserting a row which will be ignored:
INSERT IGNORE INTO `states` (`abbrev`,`other_data`) VALUES ('AK','duplicate!');
> OK
SELECT LAST_INSERT_ID();
> "0"
// oops, it already exists!
SELECT id FROM `states` WHERE `abbrev` = 'AK'; // our UNIQUE constraint here
> "2"
// there we go!
Alternately, there is a possible workaround to do this in one step - use REPLACE INTO instead of INSERT IGNORE INTO - the syntax is very similar. Note however that there are side effects with this approach - these may or may not be important to you:
REPLACE deletes+recreates the row
so DELETE triggers are, um, triggered
also, the primary ID will be incremented even if the row exists
INSERT IGNORE keeps the old row data, REPLACE replaces it with new row data
Try using ON DUPLICATE KEY instead of INSERT IGNORE, maybe this can work for you:
INSERT INTO your_table (`id`,`val`) VALUES(1,'Foo') ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(`id`);
SELECT LAST_INSERT_ID();
Also see related question: MySQL ON DUPLICATE KEY - last insert id?