2

I have a vector of values

vector = [ 10, 11, 10, 11, 12 ];

and an initialized database table

enter image description here

My goal is to update the value of each row ( which is initialized to -1 ) with a value from the vector. So the id =1, will have value 10, the id = 2, value 11 etc.

I can do this in a loop, ie for every value in vector update the corresponding row.

However I was wondering if I can do this with one update statement. I am using MySQL.

The final state after the update should be:

enter image description here

The Nth row (sorted) in the database should have the Nth value of the vector.

6
  • Is the id a primary key in your table? and What would the value of id in the 3rd record be? Commented May 16, 2018 at 8:04
  • Yes id is the primary key. The value of the the Nth record would be the (Nth-1) value in the vector (assuming the vector index starts from 0) Commented May 16, 2018 at 8:06
  • I see duplicate entries in the vector, and since the id is a primary key the update cannot be done. Commented May 16, 2018 at 8:08
  • Please show the expected end result donc use "etc" to describe it, as in your case there could be many solutions. Commented May 16, 2018 at 8:11
  • @Nerevar I added a print screen, to show the final state. Commented May 16, 2018 at 8:16

3 Answers 3

3

I suggest you transform your vector into a table :

CREATE TEMPORARY TABLE Vectors(
ID int NOT NULL AUTO_INCREMENT,
Value int not null)

INSERT INTO Vectors VALUES(10),(11),(10) ...

UPDATE MyTable AS T 
INNER JOIN Vectors AS V ON V.ID=T.ID 
SET T.Value = V.Value 
WHERE T.Value = -1

DROP TEMPORARY TABLE Vectors
Sign up to request clarification or add additional context in comments.

Comments

2

You could do the following (as far as I know it is impossible to do this with an update statement):

INSERT INTO table (id,value) VALUES (1,10),(2,11),(3,10),(4,11),(5,12)
ON DUPLICATE KEY UPDATE value=VALUES(value)

What does it do is an insert statement that checks if key already exists, if so it will update the row.

Comments

2

TRY THIS: I think we can achieve this through UNION ALL in a single query

UPDATE test t
INNER JOIN (
            SELECT 1 id, 10 val UNION ALL
            SELECT 2 id, 11 val UNION ALL
            SELECT 3 id, 10 val UNION ALL
            SELECT 4 id, 11 val UNION ALL
            SELECT 5 id, 12 val) vector ON vector.id = t.id
SET t.val = vector.val           
WHERE t.val = -1;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.