1

I would like to update my table with WHERE clause equals to result in my Subquery as you can see in the query below. The result after executing of query should be that the row with name Robert will have value to 1

CREATE TABLE `table1`(
  `name` varchar(30),
  `surname` varchar(30),
  `nextname` varchar(30),
  `value` bit(1)
);



INSERT INTO `table1` 
VALUES
  ('Daniel', 'Hanks', 'Robert', 0),
  ('Robert', 'Pitt', 'Angelina', 0),
  ('Angelina', 'Jolie', 'Monica', 0),
  ('Monica', 'Red', null, 0);



UPDATE `table1` SET `value` = 1 
WHERE `name` IN (SELECT `nextname` FROM `table1`
WHERE `name` = 'Daniel')¨

Thanks

0

3 Answers 3

3

You can't UPDATE and SELECT from the same table in one query. But MySQL does support UPDATE with JOIN syntax:

UPDATE table1 AS t1
INNER JOIN table1 AS t2 ON t1.name = t2.nextname
SET t1.value = 1 
WHERE t2.name = 'Daniel'
Sign up to request clarification or add additional context in comments.

Comments

1

You can also do it with an ugly trick:

UPDATE `table1` SET `value` = 1 
WHERE `name` IN (SELECT `nextname` FROM(SELECT `nextname` FROM `table1`
WHERE `name` = 'Daniel')x)

1 Comment

Thanks. I tried this but the version with JOIN is better to understand to me :)
0

Your syntax for using a subquery in the WHERE clause is correct. However what are you trying to do exactly? You can achieve the same result without the subquery.

UPDATE `table1` SET `value` = 1 WHERE `name` = 'Daniel'

2 Comments

Yes, but it was only for example, so the reason why i wrote my query was that i wanted to show what i meant.
This does not achieve the same result. It doesn't update the row for 'Robert'.

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.