MySQL INSERT multiple rows with same WHERE clause - mysql

I am currently able to insert rows into a table using the following SQL:
INSERT INTO ots (score_id,tab_id) VALUES ((SELECT id FROM score WHERE score_id = 11),(SELECT tab_id FROM tab WHERE layover_state = 7))
INSERT INTO ots (score_id,tab_id) VALUES ((SELECT id FROM score WHERE score_id = 12),(SELECT tab_id FROM tab WHERE layover_state = 7))
INSERT INTO ots (score_id,tab_id) VALUES ((SELECT id FROM score WHERE score_id = 19),(SELECT tab_id FROM tab WHERE layover_state = 9))
INSERT INTO ots (score_id,tab_id) VALUES ((SELECT id FROM score WHERE score_id = 27),(SELECT tab_id FROM tab WHERE layover_state = 10))
INSERT INTO ots (score_id,tab_id) VALUES ((SELECT id FROM score WHERE score_id = 45),(SELECT tab_id FROM tab WHERE layover_state = 10))
INSERT INTO ots (score_id,tab_id) VALUES ((SELECT id FROM score WHERE score_id = 51),(SELECT tab_id FROM tab WHERE layover_state = 10))
INSERT INTO ots (score_id,tab_id) VALUES ((SELECT id FROM score WHERE score_id = 52),(SELECT tab_id FROM tab WHERE layover_state = 11))
The above INSERT INTO statements work correctly. However, they seem very inefficient since there should be some way to do this with lists that capture all the integers I need to specify as part of the nested SELECT statements. However, I am not sure how to put score_id into a SQL list while also preserving the order of layover_state in a separate list.
Question
Is there a way to replace the above lines of code with one line that uses 2 SQL lists for the numbers?
Additional Information:
I am using MySQL with MySQL Workbench.

Related

Order of INSERT or UPDATE in a transaction in binlog

I'm using debezium connector to stream my Mysql binlog change records to Kafka Topic. My transaction is like so:
Tx begin
Insert INTO Project(Name, InProgress) VALUES ('New Project', 0);
-- We get the created id (say PID)
Insert INTO Tasks(TaskName, ProjectID) VALUES ('Task A', PID);
-- We get the taskID (say TID1)
Insert INTO Tasks(TaskName, ProjectID) VALUES ('Task B', PID);
-- We get the taskID (say TID2)
UPDATE Tasks SET TaskName = 'Task C' where ID = TID2;
Update Project SET InProgress = 1 where ID = PID;
Tx end
My question is in what order will I get the bin log records? Will I get the records in the order in which the records are inserted? So like this?
NEW Project with ID = PID
NEW Task with ID = TID1
NEW Task with ID = TID2
Is this documented anyplace?

MySql Insert Dynamic Query with Nested Select

I'm trying a MySQL Insert Query with mix of static & Dynamic Values. The INSERT command is.
INSERT INTO ebdb.requestaction(RequestID,
ActionID,
TransactionID,
IsActive,
IsComplete)
VALUES (
1,
**Dynamic Value from Below Query,
Dynamic Value from Below Query,**
1,
0);
The Query to fetch the field 2 & 3 come from the below Query.
SELECT transitionaction.TransitionID, transitionaction.ActionID
FROM transitionaction
INNER JOIN transition
ON transitionaction.TransitionID = transition.TransitionID
WHERE transition.TenantID = 1
AND transition.ProcessID = 1
AND transition.CurrentStateID = 1
ORDER BY transitionaction.TransitionID;
I'm doing something wrong in here.
Please guide me as to how this can be achieved in the most optimized way.
You can select static values as part of a query, e.g.:
INSERT INTO ebdb.requestaction(RequestID, ActionID, TransactionID, IsActive, IsComplete)
SELECT 1, transitionaction.ActionID, transitionaction.TransitionID, 1, 0
FROM transitionaction
INNER JOIN transition
ON transitionaction.TransitionID = transition.TransitionID
WHERE transition.TenantID = 1
AND transition.ProcessID = 1
AND transition.CurrentStateID = 1
ORDER BY transitionaction.TransitionID;
For more information, refer to MySQL's Insert...Select Syntax

Insert only if new value is the highest

Player 1 has finished a game and got a score of 10. We should save this score only if it's the high score for that user. How could I accomplish this in a single query?
I tried this:
INSERT INTO highscore("score", "player") values(10, 1)
WHERE (SELECT MAX(score) as hs FROM highscore WHERE player = 1) < 10;
Thanks
The ugly thing is that mysql does not support insert into values with where condition, but you can cheat by doing this:
INSERT INTO highscore (score, player)
SELECT 10, 1 FROM dual
WHERE (SELECT max(score) FROM highscore WHERE player = 1) < 10
This will insert no rows if the score is higher than 10, otherwise it will create a row with the values you need. It's also easier than a trigger and i believe it also has a lower cost.
Make uniq index on player. Then make insert update statement with Max () function. This can help if you are using mysql.
something like this:
Alter table highscore add uniq key (player);
Insert into highscore (player, score) values (1,10)
on duplicate update
Score = max (score,10)
INSERT INTO `max_score`
SELECT 77, 7 FROM `max_score` WHERE NOT EXISTS
(SELECT * FROM `max_score` WHERE id = 77 AND score >= 7) LIMIT 1;
(77 is the id, and 7 is the score.)
This will insert if there are no values greater than or equal to 7 with and id equal to 77, and will NOT insert if there are values greater than 7.
And with prepared statements and a timestamp:
<?php
$id = 77;
$score = 13;
$date = new DateTime();
$timestamp = $date->format('Y-m-d H:i:s');
$sql = <<<EOT
INSERT INTO `max_score`
SELECT ?, ?, ? FROM `max_score` WHERE NOT EXISTS
(SELECT * FROM `max_score` WHERE id = ? AND score >= ?) LIMIT 1;
EOT;
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('iisii', $id, $score, $timestamp, $id, $score);
$stmt->execute();
?>
(One caveat: table max_score must have at least one record in it for the SELECT ?, ? FROMmax_score` to return the provided values.)
Inspired by: MySQL: Insert record if not exists in table

SQL - Update multiple records in one query

I have table - config.
Schema:
config_name | config_value
And I would like to update multiple records in one query. I try like that:
UPDATE config
SET t1.config_value = 'value'
, t2.config_value = 'value2'
WHERE t1.config_name = 'name1'
AND t2.config_name = 'name2';
but that query is wrong :(
Can you help me?
Try either multi-table update syntax
UPDATE config t1 JOIN config t2
ON t1.config_name = 'name1' AND t2.config_name = 'name2'
SET t1.config_value = 'value',
t2.config_value = 'value2';
Here is a SQLFiddle demo
or conditional update
UPDATE config
SET config_value = CASE config_name
WHEN 'name1' THEN 'value'
WHEN 'name2' THEN 'value2'
ELSE config_value
END
WHERE config_name IN('name1', 'name2');
Here is a SQLFiddle demo
You can accomplish it with INSERT as below:
INSERT INTO mytable (id, a, b, c)
VALUES (1, 'a1', 'b1', 'c1'),
(2, 'a2', 'b2', 'c2'),
(3, 'a3', 'b3', 'c3'),
(4, 'a4', 'b4', 'c4'),
(5, 'a5', 'b5', 'c5'),
(6, 'a6', 'b6', 'c6')
ON DUPLICATE KEY UPDATE id=VALUES(id),
a=VALUES(a),
b=VALUES(b),
c=VALUES(c);
This insert new values into table, but if primary key is duplicated (already inserted into table) that values you specify would be updated and same record would not be inserted second time.
in my case I have to update the records which are more than 1000, for this instead of hitting the update query each time I preferred this,
UPDATE mst_users
SET base_id = CASE user_id
WHEN 78 THEN 999
WHEN 77 THEN 88
ELSE base_id END WHERE user_id IN(78, 77)
78,77 are the user Ids and for those user id I need to update the base_id 999 and 88 respectively.This works for me.
instead of this
UPDATE staff SET salary = 1200 WHERE name = 'Bob';
UPDATE staff SET salary = 1200 WHERE name = 'Jane';
UPDATE staff SET salary = 1200 WHERE name = 'Frank';
UPDATE staff SET salary = 1200 WHERE name = 'Susan';
UPDATE staff SET salary = 1200 WHERE name = 'John';
you can use
UPDATE staff SET salary = 1200 WHERE name IN ('Bob', 'Frank', 'John');
maybe for someone it will be useful
for Postgresql 9.5 works as a charm
INSERT INTO tabelname(id, col2, col3, col4)
VALUES
(1, 1, 1, 'text for col4'),
(DEFAULT,1,4,'another text for col4')
ON CONFLICT (id) DO UPDATE SET
col2 = EXCLUDED.col2,
col3 = EXCLUDED.col3,
col4 = EXCLUDED.col4
this SQL updates existing record and inserts if new one (2 in 1)
Camille's solution worked. Turned it into a basic PHP function, which writes up the SQL statement. Hope this helps someone else.
function _bulk_sql_update_query($table, $array)
{
/*
* Example:
INSERT INTO mytable (id, a, b, c)
VALUES (1, 'a1', 'b1', 'c1'),
(2, 'a2', 'b2', 'c2'),
(3, 'a3', 'b3', 'c3'),
(4, 'a4', 'b4', 'c4'),
(5, 'a5', 'b5', 'c5'),
(6, 'a6', 'b6', 'c6')
ON DUPLICATE KEY UPDATE id=VALUES(id),
a=VALUES(a),
b=VALUES(b),
c=VALUES(c);
*/
$sql = "";
$columns = array_keys($array[0]);
$columns_as_string = implode(', ', $columns);
$sql .= "
INSERT INTO $table
(" . $columns_as_string . ")
VALUES ";
$len = count($array);
foreach ($array as $index => $values) {
$sql .= '("';
$sql .= implode('", "', $array[$index]) . "\"";
$sql .= ')';
$sql .= ($index == $len - 1) ? "" : ", \n";
}
$sql .= "\nON DUPLICATE KEY UPDATE \n";
$len = count($columns);
foreach ($columns as $index => $column) {
$sql .= "$column=VALUES($column)";
$sql .= ($index == $len - 1) ? "" : ", \n";
}
$sql .= ";";
return $sql;
}
Execute the code below to update n number of rows, where Parent ID is the id you want to get the data from and Child ids are the ids u need to be updated so it's just u need to add the parent id and child ids to update all the rows u need using a small script.
UPDATE [Table]
SET column1 = (SELECT column1 FROM Table WHERE IDColumn = [PArent ID]),
column2 = (SELECT column2 FROM Table WHERE IDColumn = [PArent ID]),
column3 = (SELECT column3 FROM Table WHERE IDColumn = [PArent ID]),
column4 = (SELECT column4 FROM Table WHERE IDColumn = [PArent ID]),
WHERE IDColumn IN ([List of child Ids])
Execute the below code if you want to update all record in all columns:
update config set column1='value',column2='value'...columnN='value';
and if you want to update all columns of a particular row then execute below code:
update config set column1='value',column2='value'...columnN='value' where column1='value'
Assuming you have the list of values to update in an Excel spreadsheet with config_value in column A1 and config_name in B1 you can easily write up the query there using an Excel formula like
=CONCAT("UPDATE config SET config_value = ","'",A1,"'", " WHERE config_name = ","'",B1,"'")
INSERT INTO tablename
(name, salary)
VALUES
('Bob', 1125),
('Jane', 1200),
('Frank', 1100),
('Susan', 1175),
('John', 1150)
ON DUPLICATE KEY UPDATE salary = VALUES(salary);
UPDATE 2021 / MySql v8.0.20 and later
The most upvoted answer advises to use the VALUES function which is now DEPRECATED for the ON DUPLICATE KEY UPDATE syntax. With v8.0.20 you get a deprecation warning with the VALUES function:
INSERT INTO chart (id, flag)
VALUES (1, 'FLAG_1'),(2, 'FLAG_2')
ON DUPLICATE KEY UPDATE id = VALUES(id), flag = VALUES(flag);
[HY000][1287] 'VALUES function' is deprecated and will be removed in a future release. Please use an alias (INSERT INTO ... VALUES (...) AS alias) and replace VALUES(col) in the ON DUPLICATE KEY UPDATE clause with alias.col instead
Use the new alias syntax instead:
official MySQL worklog
Docs
INSERT INTO chart (id, flag)
VALUES (1, 'FLAG_1'),(2, 'FLAG_2') AS aliased
ON DUPLICATE KEY UPDATE flag=aliased.flag;
just make a transaction statement, with multiple update statement and commit. In error case, you can just rollback modification handle by starting transaction.
START TRANSACTION;
/*Multiple update statement*/
COMMIT;
(This syntax is for MySQL, for PostgreSQL, replace 'START TRANSACTION' by 'BEGIN')
Try either multi-table update syntax
Try it copy and SQL query:
CREATE TABLE #temp (id int, name varchar(50))
CREATE TABLE #temp2 (id int, name varchar(50))
INSERT INTO #temp (id, name)
VALUES (1,'abc'), (2,'xyz'), (3,'mno'), (4,'abc')
INSERT INTO #temp2 (id, name)
VALUES (2,'def'), (1,'mno1')
SELECT * FROM #temp
SELECT * FROM #temp2
UPDATE t
SET name = CASE WHEN t.id = t1.id THEN t1.name ELSE t.name END
FROM #temp t
INNER JOIN #temp2 t1 on t.id = t1.id
select * from #temp
select * from #temp2
drop table #temp
drop table #temp2
UPDATE table name SET field name = 'value' WHERE table name.primary key
If you need to update several rows at a time, the alternative is prepared statement:
database complies a query pattern you provide the first time, keep the compiled result for current connection (depends on implementation).
then you updates all the rows, by sending shortened label of the prepared function with different parameters in SQL syntax, instead of sending entire UPDATE statement several times for several updates
the database parse the shortened label of the prepared function , which is linked to the pre-compiled result, then perform the updates.
next time when you perform row updates, the database may still use the pre-compiled result and quickly complete the operations (so the first step above can be omitted since it may take time to compile).
Here is PostgreSQL example of prepare statement, many of SQL databases (e.g. MariaDB,MySQL, Oracle) also support it.

Cancel Insert if inner query find nothing

I got the following query :
INSERT INTO contracts_settings (contract_id, setting_id, setting_value)
VALUES (:contract_id, (
SELECT setting_id
FROM settings
WHERE setting_type = :setting_type
AND setting_name = :setting_name
LIMIT 1
), :setting_value)
ON DUPLICATE KEY UPDATE setting_value = :setting_value
The value with the prefix : is replaced with data using PHP PDO::bindBalue.
If the inner query find nothing (it return NULL) but also INSERT a NULL statement. How to avoid that ?
Thanks.
Convert the INSERT ... VALUES syntax to INSERT ... SELECT:
INSERT INTO contracts_settings
(contract_id, setting_id, setting_value)
SELECT
:contract_id,
setting_id,
:setting_value
FROM settings
WHERE setting_type = :setting_type
AND setting_name = :setting_name
LIMIT 1
ON DUPLICATE KEY UPDATE
setting_value = :setting_value ;