mysql - conditional insert row within a query with ON DUPLICATE KEY UPDATE - mysql

I have a complex query with a ON DUPLICATE KEY Update inside. I only want to insert the last value if there is no row with “timestamp_dag” = 1420070400, if there is a row with that condition I want to do nothing.
INSERT INTO data_prijzen_advertentie (
`ID_advertentie`,`jaar`,`rijnr`,`status_prijs`,`datum_dag`,`timestamp_dag`,
`prijs_maand`,`prijs_week`,`prijs_midweek`,`prijs_langweekend`,`prijs_weekend`,
`prijs_dag`,`prijs_ochtend`,`prijs_middag`
)
VALUES
(100,2014,1,1,'12-05-2014',1399852800,0,100,0,75,0,0,0,0),
(100,2014,2,1,'23-05-2014',1400803200,0,75,0,101,0,0,0,0),
(100,2014,3,1,'30-05-2014',1401408000,0,100,0,75,0,0,0,0),
(100,2014,4,1,'01-01-2015',1420070400,0,0,0,0,0,0,0,0)
ON DUPLICATE KEY UPDATE
status_prijs = VALUES(status_prijs), datum_dag = VALUES(datum_dag),
timestamp_dag = VALUES(timestamp_dag), prijs_maand = VALUES(prijs_maand),
prijs_week = VALUES(prijs_week), prijs_midweek = VALUES(prijs_midweek),
prijs_langweekend = VALUES(prijs_langweekend), prijs_weekend = VALUES(prijs_weekend),
prijs_dag = VALUES(prijs_dag), prijs_ochtend = VALUES(prijs_ochtend),
prijs_middag = VALUES(prijs_middag);

it's the best if you can handle this before the query string creation..
but if you can't, and your exceptional value is static, you can try something like this:
(I haven't tried to run it yet though)
INSERT INTO data_prijzen_advertentie (
`ID_advertentie`,`jaar`,`rijnr`,`status_prijs`,`datum_dag`,`timestamp_dag`,
`prijs_maand`,`prijs_week`,`prijs_midweek`,`prijs_langweekend`,`prijs_weekend`,
`prijs_dag`,`prijs_ochtend`,`prijs_middag`
)
VALUES
(100,2014,1,1,'12-05-2014',1399852800,0,100,0,75,0,0,0,0),
(100,2014,2,1,'23-05-2014',1400803200,0,75,0,101,0,0,0,0),
(100,2014,3,1,'30-05-2014',1401408000,0,100,0,75,0,0,0,0),
(100,2014,4,1,'01-01-2015',1420070400,0,0,0,0,0,0,0,0)
ON DUPLICATE KEY UPDATE
status_prijs = IF(timestamp_dag<>1420070400, VALUES(status_prijs), status_prijs),
datum_dag = IF(timestamp_dag<>1420070400, VALUES(datum_dag), datum_dag),
timestamp_dag = IF(timestamp_dag<>1420070400, VALUES(timestamp_dag), timestamp_dag),
prijs_maand = IF(timestamp_dag<>1420070400, VALUES(prijs_maand), prijs_maand),
prijs_week = IF(timestamp_dag<>1420070400, VALUES(prijs_week), prijs_week),
prijs_midweek = IF(timestamp_dag<>1420070400, VALUES(prijs_midweek), prijs_midweek),
prijs_langweekend = IF(timestamp_dag<>1420070400, VALUES(prijs_langweekend), prijs_langweekend),
prijs_weekend = IF(timestamp_dag<>1420070400, VALUES(prijs_weekend), prijs_weekend),
prijs_dag = IF(timestamp_dag<>1420070400, VALUES(prijs_dag), prijs_dag),
prijs_ochtend = IF(timestamp_dag<>1420070400, VALUES(prijs_ochtend), prijs_ochtend),
prijs_middag = IF(timestamp_dag<>1420070400, VALUES(prijs_middag), prijs_middag);

You will only have the ON DUPLICATE KEY UPDATE ... portion run if the timestamp_dag matches the criteria for triggering it. From the MySQL docs:
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.
So assuming your table is built this way, then the update will trigger.
You can add a UNIQUE index using the syntax as described here.
CREATE UNIQUE INDEX ind_unique_timestamp_dag ON data_prijzen_advertentie (timestamp_dag)

Related

Update the key value of a json field in mysql

I have the following json field
{
"Covid-19Vaccine Staus": "Not vaccinated (intent to in the future)",
"Date of last vaccine taken": "2021-08-09T00:00:00+04:00",
"If vaccinated, Name of vaccination received": "Other WHO Approved vaccine"
}
What i would like to do is update the key description i.e. Covid-19 Vaccine Staus to Covid19VaccineStaus.
On doing a direct update to the field on mysql workbench it generates the following query,
UPDATE `my_json_table` SET `containerValue` = '{\"Covid19VaccineStaus\": \"Vaccinated\", \"Date of last vaccine taken\": \"2021-07-13T00:00:00+04:00\", \"If vaccinated, Name of vaccination received\": \"Pfizer-BioNTech\"}' WHERE (`id` = '94');
where it looks like it takes the entire values for the field and then does the update.
What should the query look like if i want to update just the Covid19VaccineStatus key without putting in the values for the other data points for the json schema.
Please take a look at JSON functions
JSON_REPLACE,
Replace values in JSON document
JSON_REMOVE,
Remove data from JSON document
JSON_INSERT
Insert data into JSON document
UPDATE `my_json_table` SET `containerValue` = JSON_REPLACE(`containerValue`, '$."Covid-19Vaccine Staus"', 'Vaccinated') WHERE (`id` = '94');
UPDATE `my_json_table` SET `containerValue` = JSON_REMOVE(`containerValue`, '$."Covid-19Vaccine Staus"') WHERE (`id` = '94');
UPDATE `my_json_table` SET `containerValue` = JSON_INSERT(`containerValue`, '$."Covid-19Vaccine Staus"', 'Vaccinated') WHERE (`id` = '94');
To replace a key and keep value
UPDATE `my_json_table`
SET `containerValue` =
JSON_REMOVE(
JSON_INSERT(`containerValue`, '$."Covid19VaccineStaus"',
JSON_EXTRACT(`containerValue`, '$."Covid-19Vaccine Staus"')),
'$."Covid-19Vaccine Staus"')
WHERE (`id` = '94');
You can use JSON_SET which handles both insert and update actions.
UPDATE my_json_table
SET containerValue = JSON_SET(containerValue, '$."Covid-19Vaccine Staus"', 'Vaccinated')
WHERE id = 94;
So if your key does not exist yet in your JSON, it will be inserted with the value Vaccinated. Otherwise, the value corresponding to your key will be updated.
You can also find examples here on how to handle arrays or multiple values with JSON_SET.
If you only need to update the value but not perform any insertion in your JSON if the key does not exist, you can use JSON_REPLACE.
If you only need to insert the key and the value but not perform any update in your JSON if the key already exists, you can use JSON_INSERT.
If you want to update the name of your key:
UPDATE my_json_table
SET containerValue = JSON_INSERT(
JSON_REMOVE(containerValue, '$."Covid-19Vaccine Staus"'),
'$.Covid19VaccineStaus',
JSON_EXTRACT(containerValue, '$."Covid-19Vaccine Staus"')
)
WHERE id = 94;

how to update with , seprator with preivous value in mysql

$r ='insert into posts set id="'.$id.'", postId="'.$idus.'" ON DUPLICATE KEY UPDATE whoLikes= whoLikes,$idus'
like := ON DUPLICATE KEY UPDATE new = new+'$new'
but i need:= ON DUPLICATE KEY UPDATE new = new,'$new'
You should be using MySQL concat() function:
... ON DUPLICATE KEY UPDATE `whoLikes`=CONCAT(`whoLikes`, $idus)

MYSQL ONDUPLICATE KEY UPDATE ISSUE

I am trying to use 'ON DUPLICATE KEY UPDATE' statement to update column when duplicate primary key are already in table.
but even if table has duplicated primary key, it does not update column.
below is 'ON DUPLICATE KEY UPDATE' statement.
is there somthing wrong?
ON DUPLICATE KEY UPDATE authenticated = authenticated
and notAuthenticated = notAuthenticated
and stoped = stoped
and deleted = deleted
and updatedDate = now()
;
use VALUES(Column) and replace all this AND with comma ,:
ON DUPLICATE KEY UPDATE authenticated = VALUES(authenticated),
notAuthenticated = VALUES(notAuthenticated),
stoped = VALUES(stoped),
deleted = VALUES(deleted),
updatedDate = now()
Don't use AND, but use commas:
ON DUPLICATE KEY UPDATE
authenticated = VALUES(authenticated),
notAuthenticated = VALUES(notAuthenticated),
stoped = VALUES(stoped),
deleted = VALUES(deleted),
updatedDate = now()

UPDATE multiple rows with different values in one query in MySQL

I am trying to understand how to UPDATE multiple rows with different values and I just don't get it. The solution is everywhere but to me it looks difficult to understand.
For instance, three updates into 1 query:
UPDATE table_users
SET cod_user = '622057'
, date = '12082014'
WHERE user_rol = 'student'
AND cod_office = '17389551';
UPDATE table_users
SET cod_user = '2913659'
, date = '12082014'
WHERE user_rol = 'assistant'
AND cod_office = '17389551';
UPDATE table_users
SET cod_user = '6160230'
, date = '12082014'
WHERE user_rol = 'admin'
AND cod_office = '17389551';
I read an example, but I really don't understand how to make the query. i.e:
UPDATE table_to_update
SET cod_user= IF(cod_office = '17389551','622057','2913659','6160230')
,date = IF(cod_office = '17389551','12082014')
WHERE ?? IN (??) ;
I'm not entirely clear how to do the query if there are multiple condition in the WHERE and in the IF condition..any ideas?
You can do it this way:
UPDATE table_users
SET cod_user = (case when user_role = 'student' then '622057'
when user_role = 'assistant' then '2913659'
when user_role = 'admin' then '6160230'
end),
date = '12082014'
WHERE user_role in ('student', 'assistant', 'admin') AND
cod_office = '17389551';
I don't understand your date format. Dates should be stored in the database using native date and time types.
MySQL allows a more readable way to combine multiple updates into a single query. This seems to better fit the scenario you describe, is much easier to read, and avoids those difficult-to-untangle multiple conditions.
INSERT INTO table_users (cod_user, date, user_rol, cod_office)
VALUES
('622057', '12082014', 'student', '17389551'),
('2913659', '12082014', 'assistant','17389551'),
('6160230', '12082014', 'admin', '17389551')
ON DUPLICATE KEY UPDATE
cod_user=VALUES(cod_user), date=VALUES(date)
This assumes that the user_rol, cod_office combination is a primary key. If only one of these is the primary key, then add the other field to the UPDATE list.
If neither of them is a primary key (that seems unlikely) then this approach will always create new records - probably not what is wanted.
However, this approach makes prepared statements easier to build and more concise.
UPDATE table_name
SET cod_user =
CASE
WHEN user_rol = 'student' THEN '622057'
WHEN user_rol = 'assistant' THEN '2913659'
WHEN user_rol = 'admin' THEN '6160230'
END, date = '12082014'
WHERE user_rol IN ('student','assistant','admin')
AND cod_office = '17389551';
You can use a CASE statement to handle multiple if/then scenarios:
UPDATE table_to_update
SET cod_user= CASE WHEN user_rol = 'student' THEN '622057'
WHEN user_rol = 'assistant' THEN '2913659'
WHEN user_rol = 'admin' THEN '6160230'
END
,date = '12082014'
WHERE user_rol IN ('student','assistant','admin')
AND cod_office = '17389551';
To Extend on #Trevedhek answer,
In case the update has to be done with non-unique keys, 4 queries will be need
NOTE: This is not transaction-safe
This can be done using a temp table.
Step 1: Create a temp table keys and the columns you want to update
CREATE TEMPORARY TABLE temp_table_users
(
cod_user varchar(50)
, date varchar(50)
, user_rol varchar(50)
, cod_office varchar(50)
) ENGINE=MEMORY
Step 2: Insert the values into the temp table
Step 3: Update the original table
UPDATE table_users t1
JOIN temp_table_users tt1 using(user_rol,cod_office)
SET
t1.cod_office = tt1.cod_office
t1.date = tt1.date
Step 4: Drop the temp table
In php, you use multi_query method of mysqli instance.
$sql = "SELECT COUNT(*) AS _num FROM test;
INSERT INTO test(id) VALUES (1);
SELECT COUNT(*) AS _num FROM test; ";
$mysqli->multi_query($sql);
comparing result to transaction, insert, case methods in update 30,000 raw.
Transaction: 5.5194580554962
Insert: 0.20669293403625
Case: 16.474853992462
Multi: 0.0412278175354
As you can see, multiple statements query is more efficient than the highest answer.
Just in case if you get error message like this:
PHP Warning: Error while sending SET_OPTION packet
You may need to increase the max_allowed_packet in mysql config file.
UPDATE Table1 SET col1= col2 FROM (SELECT col2, col3 FROM Table2) as newTbl WHERE col4= col3
Here col4 & col1 are in Table1. col2 & col3 are in Table2 I Am trying to update each col1 where col4 = col3 different value for each row
I did it this way:
<update id="updateSettings" parameterType="PushSettings">
<foreach collection="settings" item="setting">
UPDATE push_setting SET status = #{setting.status}
WHERE type = #{setting.type} AND user_id = #{userId};
</foreach>
</update>
where PushSettings is
public class PushSettings {
private List<PushSetting> settings;
private String userId;
}
it works fine

ON DUPLICATE KEY UPDATE only if second condition true

How do i update only if a second condition is true, it seems my version of mysql doesnt allow a WHERE at the end of ON DUPLICATE syntax.
INSERT INTO `proxies` (`proxy`,`response`,`PAYMENT`,`type`,`country`,`status`,`tier`,`last_checked`,`last_active`,`response_time`)
VALUES ('111.9.204.96:8123','200','coolproxies','anon','China','active','3','1400624136','1400624136','1.577639')
ON DUPLICATE KEY UPDATE `response`='200',`response_time`='1.577639',`type`='anon',`country`='China',`status`='active',`tier`='2',`last_checked`='1400624137'
this works ok, but I need to only update when WHERE last_checked < '1400624137' is true.
This is what the query that does this looks like.
INSERT INTO `proxies` (`proxy`,`response`,`PAYMENT`,`type`,`country`,`status`,`tier`,`last_checked`,`last_active`,`response_time`)
VALUES ('207.204.249.193:21320','200','scanner','anon','United States','active','1','1400633866','1400633866','1.59696')
ON DUPLICATE KEY UPDATE
`response_time` = IF(`last_checked` < '1400633866', '1.59696', `response_time`),
`status` = IF(`last_checked` < '1400633866', 'active', `status`),
`last_checked` = IF(`last_checked` < '1400633866', '1400633866', `last_checked`),
`last_active` = IF(`last_checked` < '1400633866', '1400633866', `last_active`);
An alternative to doing it in 2 queries as #GordonLinoff mentioned, is to use the method described in this related question you can use an IF to update based on a condition.
INSERT INTO `proxies` (...)
VALUES (...)
ON DUPLICATE KEY UPDATE
my_column = IF(last_checked < '1400624137', VALUES(my_column), my_column)
Basically what the IF does is when TRUE then update the field to the new value, otherwise if FALSE set it to the current value, which means no change to your existing data.
I think you need to do this as two statements:
update . . .
where last_checked < '1400624137';
insert ignore into proxies(. . .);
(or use on duplicate key update to do nothing).