Query:
INSERT INTO `metadata` (`group_id`, `key`, `value`)
VALUES ("19", "originality", "2")
ON DUPLICATE KEY UPDATE (`group_id` = `19`, `key`=`originality`, `value`=`2`)
The table:
group_id | key | value
----------------------------------------
group_id and key both have a UNIQUE index.
The error happens when I try to run the query when a row already exists with the id 19. The way I want the query to function is, if there is no row with that id, insert it and if there is update it instead of inserting a new row.
The error message I get is the typical:
I'm not sure if a ( should follow the UPDATE keyword - I think not. So try
ON DUPLICATE KEY UPDATE `group_id` = 19, `key`='originality', `value`=2
(or replace group_id with submission_group_id - your error message doesn't seem to match the original query)
you can only use ` on table columns and table names, not for data.
data should use ' or "
like:
ON DUPLICATE KEY UPDATE `group_id` = 19, `key`="originality", `value`=2
The quote tag must be the ' character not the ` character.
if there is no row with that id, insert it and if there is update it instead of inserting a new row.
If you want to do this you should try statement like:
IF EXISTS (SELECT * FROM sometable WHERE ColumnName='somevalue')
UPDATE sometable SET (...) WHERE ColumnName='somevalue'
ELSE
INSERT INTO Table1 VALUES (...)
Related
I have a query that need to insert values in a table and update them if the key already exists.
This request is the following:
INSERT INTO table1(`id`, `day`, `quantity`, `residue`)
SELECT
id,
SUBDATE(NOW(), 1) as day,
(
A SUB QUERY
) as qte,
(
ANOTHER SUB QUERY
) as r
FROM table2
ON DUPLICATE KEY UPDATE
quantity=qte,
residue=r;
This request result in the error Unknown column 'qte' in 'field list'
What did I miss ?
You want VALUES():
ON DUPLICATE KEY UPDATE
quantity = VALUES(quantity),
residue = VALUES(residue)
How this works is explained in the documentation:
In assignment value expressions in the ON DUPLICATE KEY UPDATE clause, you can use the VALUES(col_name) function to refer to column values from the INSERT portion .
If I'm inserting data into a table with the following fields:
serialNumber active country
I need to only insert duplicate serialNumbers if active is no.
So for example: I want to insert a record with serialNumber 1234.
If the serial number doesn't already exist in the table go ahead and add it. If it does already exist, check the value of 'active' active is yes then don't add the new record, if it's no then do add the record.
Any ideas how to achieve this in MYSQL?
If the table lacks the necessary unique keys and you do not have permission, or don't want to set the keys you would need, you can use this alternative:
INSERT INTO `table1`
(`field1`,
`field2`)
SELECT value1,
value2
FROM (SELECT 1) t_1
WHERE NOT EXISTS (SELECT 1
FROM `table1`
WHERE `field1` = value1
AND `field2` = value2);
For yor question it could be written as
INSERT INTO `activity`
(`serialNumbers`,
`active`)
SELECT 1234,
'yes'
FROM (SELECT 1) t_1
WHERE EXISTS (SELECT 1
FROM `activity`
WHERE `serialNumbers` = 1234
AND `active` = 'no');
You can use the ON DUPLICATE KEY statement after an INSERT INTO query to update the row if it already exists. Documentation : https://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
INSERT INTO table (serialNumber , active, country) VALUES (1010, 'no', 'FR')
ON DUPLICATE KEY UPDATE active='yes';
You can use the insert ... on duplicate key update in MySQL. It is similar to the MERGE used in other SQL databases, but MySQL does not provide the MERGE statement so this is the next best.
INSERT INTO TABLE (serialNumber, active, country)
VALUES (1234, 'active', 'GB') ON DUPLICATE KEY UPDATE country = 'ND';
Also, use INSERT IGNORE if you don't want to generate errors.
I'm trying to insert new rows into a MySQL table, but only if one of the values that I'm inserting isn't in a row that's already in the table.
For example, if I'm doing:
insert into `mytable` (`id`, `name`) values (10, `Fred`)
I want to be able to check to see if any other row in the table already has name = 'Fred'. How can this be done?
Thanks!
EDIT
What I tried (can't post the exact statement, but here's a representation):
INSERT IGNORE INTO mytable (`domain`, `id`)
VALUES ('i.imgur.com', '12gfa')
WHERE '12gfa' not in (
select id from mytable
)
which throws the error:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE '12gfa' not in ( select id from mytable)' at line 3
First of all, your id field should be an autoincrement, unless it's a foreign key (but I can't assume it from the code you inserted in your question).
In this way you can be sure to have a unique value for id for each row.
If it's not the case, you should create a primary key for the table that includes ALL the fields you don't want to duplicate and use the INSERT IGNORE command.
Here's a good read about what you're trying to achieve.
You could use something like this
INSERT INTO someTable (someField, someOtherField)
VALUES ("someData", "someOtherData")
ON DUPLICATE KEY UPDATE someOtherField=VALUES("betterData");
This will insert a new row, unless a row already exists with a duplicate key, it will update it.
DELIMITER |
CREATE PROCEDURE tbl_update (IN id INT, IN nm VARCHAR(15))
BEGIN
DECLARE exst INT;
SELECT count(name) INTO exst FROM mytable WHERE name = nm;
IF exst = 0 THEN
INSERT INTO mytable VALUES(id, name);
END IF;
END
|
DELIMITER ;
or just make an attribute name as UNIQUE
I have a simple table like this
CREATE TABLE authid(
id INT NOT NULL AUTO_INCREMENT,
authid VARCHAR(128) NOT NULL UNIQUE,
PRIMARY KEY(id)
);
Now if I insert a value with
INSERT INTO authid(authid) VALUES('test');
It will work fine and return the inserted id the first time, but if I do it again when the authid already exists (notice that we have authid marked as UNIQUE) it will return an error.
Is there a way achieve this this in one SQL statement: Insert it, get the id and if it already exists, still get the id.
Take a look at this: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
If you're using MySQL 5.0 or higher you can use the "INSERT ... ON DUPLICATE KEY UPDATE" syntax. You may be able to combine that with LAST_INSERT_ID() (I'm not positive about that)
So:
insert into authid (authid) values ('test') on duplicate key update id=LAST_INSERT_ID(id), authid='test';
select LAST_INSERT_ID();
Well indeed if you try to insert 2 times the same value in a UNIQUE field, it won't work, that's the point of UNIQUE fields.
If I understand well, you want to know if it's possible whether to use an INSERT or an UPDATE statement depending on the existance of an item or not ? Then you need 2 queries, 1 to test existence, the other to insert new value or update existing one
Insert the value conditionally (i.e. if it doesn't exist). Whether the insert takes place or not, by the end of the statement the result will be the same: the value will be in the table. So, just select the ID of the row that matches that value. Or, speaking in SQL, like this:
INSERT INTO authid (authid)
SELECT 'test'
WHERE NOT EXISTS (
SELECT *
FROM authid
WHERE authid = 'test'
);
SELECT id
FROM authid
WHERE authid = 'test'
;
I would like to insert a new row into my table from the output of an aggregated query:
INSERT INTO table_name (id) SELECT MAX(id) + 1 FROM table_name;
but it fails with the following error:
ERROR 1339 (20000): Case not found for CASE statement
If I add the + 1 part to the aggregate function like this:
INSERT INTO table_name (id) SELECT MAX(id + 1) FROM table_name;
it produces the same error. If I remove the + 1 part, it will of course fail because the id is the primary key:
ERROR 1062 (23000): Duplicate entry '48' for key 'PRIMARY'
How can I achieve this in MySQL 5.5.29-0ubuntu0.12.10.1 without modifying the table structure?
UPDATE
This is probably because of a missing not null field in the original table, I'll post the solution here if I'll find it out tomorrow.
since you want to increment the last id by one, why don't you use AUTO_INCREMENT column for column ID.
CREATE TABLE tableName
(
ID INT AUTO_INCREMENT PRIMARY KEY,
....
)
Although the error said differently the cause of the problem was a missing not NULL field in the insert.
Filling out every field resulted a correct MAX(id) + 1 query.