0

I want to grab a list of values from an SQL table, and then run a query using each of these values to update other fields in the same table. In another language, I'd use a for loop for this, but I've read that looping operations should be avoided/aren't supported in SQL.

Conceptually (obviously the code isn't valid), this is what I'm trying to achieve:

my_list = SELECT item_id
          FROM my_table
          WHERE value = "my_value"
          AND field_id = 1

for x in my_list:
    UPDATE my_table
    SET meta_value = "my_value"
    WHERE field_id = 2
    AND item_id = x

What's the proper way to achieve this is SQL please?

3 Answers 3

2

Try this update with join statement:

update My_Table t
JOIN My_Table s on(t.item_id = s.item_id
                   and t.field_id = 2
                   and s.field_id = 1)
set t.meta_value = 'my_value'
where s.value = 'MY_VALUE'
Sign up to request clarification or add additional context in comments.

Comments

1

this should work without using loops:

  UPDATE my_table 
  SET meta_value = "my_value" 
  WHERE field_id = 2 AND item_id IN
  (
    SELECT item_id
    FROM my_table
    WHERE value = "my_value"
    AND field_id = 1
);

4 Comments

Thanks, but this throws an error:#1093 - You can't specify target table 'my_table' for update in FROM clause
Hmmm, I tried this with an Oracle database before suggesting this solution and it worked
Obviously, you're using a MySQL datbase, so you should go for @hasumedic's answer
Probably my fault for not being specific. Thanks anyway.
0

You should be able to join the table with a subset of itself:

UPDATE my_table t1
INNER JOIN (SELECT item_id FROM my_table WHERE value = "my_value" AND field_id = 1) t2 ON t1.item_id = t2.item_id
SET t1.meta_value = "my_value"
WHERE t1.field_id = 2

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.