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.
Related
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>);
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.
Hi all I have the following query which works nicely but i know need to add the unique id generated in the insert table to the destination table
insert into claims.third_party(tp_names,tp_insurer,tp_registration)
select c.tpnames,c.tpinsurers,c.tpregistration from claims as c;
so in other words i need to return the unique id and add it to the source table creating a foreign key link
You can use LAST_INSERT_ID() to get the last auto increment value.
SELECT LAST_INSERT_ID();
http://dev.mysql.com/doc/refman/5.6/en/information-functions.html#function_last-insert-id
UPDATE:
Use ROW_COUNT() alongside LAST_INSERT_ID() and you will have the range of keys generated.
[LAST_INSERT_ID(), (LAST_INSERT_ID() + ROW_COUNT())]
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?
I am trying to implement a rating system where I keep the following two fields in my db table:
rating (the current rating)
num_rates (the number of ratings submitted so far)
UPDATE `mytable`
SET rating=((rating*num_rates)+$theRating)/num_rates, num_rates=num_rates+1
WHERE uniqueCol='$uniqueCol'
the variables are from my PHP code.
So, basically sometimes the row with the uniqueCol does not exist in the DB, so how can I do the above statement if the exists and if it doesn't then do something like this:
INSERT INTO `mytable`
SET rating=$theRating, num_rates=1, uniqueCol=$uniqueCol
Have a look at INSERT ... ON DUPLICATE KEY UPDATE.
It should look something like that:
INSERT INTO mytable (rating, num_rates, uniqueCol)
VALUES ($theRating, 1, $uniqueCol)
ON DUPLICATE KEY UPDATE
rating=((rating*num_rates)+$theRating)/num_rates,
num_rates=num_rates+1;
Make sure to have a UNIQUE index or PRIMARY KEY on your uniqueCol.