0

Here is my table:

Id Name Count

1 Apple 1

2 Peach 1

If I just have Name and MySql which is set to "Safe Update Mode"(under this mode, can't update table with out key in where terms). So I need get Id by Name at first, then update row.

In SqlServer, I can do it like below:

DELCARE @Id INT;
SELECT @Id=(SELECT Id FROM MyTable WHERE Name='Apple')

IF(@Id IS NOT NULL)
BEGIN
  UPDATE MyTable
    SET Count=2
  WHERE Id=@Id
END

In MySql, how can I do?

1 Answer 1

2

You need to use the set keyword to declare the variable, but you don't really need it.

UPDATE MyTable 
    SET Count=2
  WHERE ID IN ( SELECT * FROM (SELECT ID FROM MyTable WHERE name = 'Apple') S)

This isn't the most efficient in the world, but it functions as a work-around when the update query depends on the table it's updating.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.