MySQL insert or update with nested query - mysql

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 .

Related

insert into select on duplicate mysql query

I am trying to update on duplicate record in MySQL,
I have a table with many column but i want to update only some column from another table with same desc as current table but it is not updating records.
my query is:
insert into backup_prochart.symbol_list(ticker,end_date,cur_date)
select ticker,t.end_date,t.cur_date from prochart.symbol_list t where
ticker=t.ticker and ticker= 'MAY17' on duplicate key update
end_date=t.end_date,cur_date=t.cur_date;
another query i tried
insert into backup_prochart.symbol_list(ticker,end_date,cur_date) select t.ticker,t.end_date,t.cur_date from prochart.symbol_list t where ticker=t.ticker and t.ticker= 'MAY17' on duplicate key update end_date=t.end_date,cur_date=t.cur_date;
can anyone tell me whats wrong with my query.?
You could try :
INSERT INTO backup_prochart.symbol_list (ticker, end_date, cur_date)
SELECT ticker, end_date, cur_date FROM prochart.symbol_list WHERE ticker = 'MAY17'
ON DUPLICATE KEY UPDATE end_date = values(end_date), cur_date = values(cur_date);
Of course the column "ticker" must be defined as unique for the table "backup_prochart.symbol_list".
You say that you are trying to update a record, but you are using an INSERT statement. Shouldn't you be using UPDATE instead of INSERT?
Difference between INSERT and UPDATE can be found here
Note that you can use UPDATE and SELECT in a single query.
try this. its worked for me.
INSERT INTO employee_projects
(employee_id,
proj_ref_code)
SELECT ep.employee_id,
ep.proj_ref_code
FROM hs_hr_emp_projects_history ep
WHERE NOT EXISTS (SELECT 1
FROM employee_projects p
WHERE ep.employee_id = p.employee_id
AND ep.proj_ref_code = p.proj_ref_code)

Mysql - INSERT from SELECT with conditional ON DUPLICATE KEY UPDATE

I'm reading about conditional updates on duplicate key based on IF statements - e.g., MySQL Conditional Insert on Duplicate.
I'm trying to do something similar, but within an insert from a select:
INSERT IGNORE INTO data1 (id, date, quantity)
SELECT id, date, quantity
FROM other_table
WHERE date = '2015-03-01'
AND id=123
ON DUPLICATE KEY UPDATE
quantity = IF(quantity IS NULL, VALUES(quantity), quantity)
However, this generates an error:
#1052 - Column 'quantity' in field list is ambiguous
I can't quite figure out how to tell MySQL which 'quantity' field is which in order to resolve the ambiguity problem. Adding aliases to each table doesn't seem to help (calling data1 'd' throws a different error).
Anyone have experience with this?
You should qualify the references to the quantity field that belongs to table data1 in the ON DUPLICATE KEY UPDATE part of the query:
INSERT INTO data1 (id, date, quantity)
SELECT id, date, quantity
FROM other_table
WHERE date = '2015-03-01'
AND id=123
ON DUPLICATE KEY UPDATE
quantity = IF(data1.quantity IS NULL, VALUES(quantity), data1.quantity)
A shorter way to write this IF() expression is to use function IFNULL() or COALESCE():
ON DUPLICATE KEY UPDATE
quantity = IFNULL(data1.quantity, VALUES(quantity))
or
ON DUPLICATE KEY UPDATE
quantity = COALESCE(data1.quantity, VALUES(quantity))
Also, there is no need to use IGNORE. The errors that IGNORE converts to warnings does not happen any more because of the ON DUPLICATE KEY UPDATE clause.
mySQL doesn't know to which quantity collumn you are referring since it is present in both data1 and other_table tables.
You have to use it like this: other_table.quantity
Your query will change like this
INSERT IGNORE INTO data1 (id, date, quantity)
SELECT id, date, quantity
FROM other_table
WHERE date = '2015-03-01'
AND id=123
ON DUPLICATE KEY UPDATE
data1.quantity = IF(other_table.quantity IS NULL,
VALUES(other_table.quantity), other_table.quantity)

MySQL UPSERT not recognizing alias

I have a query that performs an UPSERT (Insert - but if exists, update).
MySQL complains it isn't valid, here is the query:
insert into
mytable (user_id, num_products_observed, num_purchased_percent)
(select
A.user_id,
B.total 'num_products_observed',
case
when A.purchased is null then 0
else A.purchased/B.total
end 'num_purchased_percent'
from
(select user_id, count(prod_observed) 'total' from products where user_id = ? ) B
left join (select user_id, count(prod_purch) 'purchased' from products_purchased) A on B.user_id = A.user_id
) newsum -- <--- ISSUE IS HERE
ON DUPLICATE KEY UPDATE
num_products_observed = newsum.num_products_observed,
num_purchased_percent = newsum.num_purchased_percent
I hope this makes sense to you. The issue is at the line which reads ) newsum. MySql complains about the alias I'm giving the table. user_id is unique in this table (mytable).
It IS possible that B.total is null, in which case everything in newsum is null - which is fine, then I don't want to insert or update anything (or an update with user_id and zeros for all would be fine too).
Any thoughts on what I'm doing wrong? Thanks
Are you trying to use VALUES statements.
You can use the VALUES(col_name) function in the UPDATE clause to refer to column values from the INSERT portion of the INSERT ... ON DUPLICATE KEY UPDATE statement
dev.mysql

Mysql query to update row if exists?

I need an If, then, else query in mysql,
tried out the below,
if exists( select * from data_table where user_id =1 and link_id = 1) then update data_table set is_view = 1 where user_id = 1 else insert into data_table...
what is the correct way to do this?
if you only need to do this in mysql, then search insert on duplicate key. Or you can use a stored procedure. Check INSERT ... ON DUPLICATE KEY UPDATE Syntax
insert into data_table (user_id, link_id, other_column)
values (1, 1, 'value to insert or uodate')
on duplicate key update other_column='value to insert or update';

Why is this MySQL query causing an error?

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 (...)