Domi.Zhang
Domi.Zhang

Reputation: 1705

How to declare variable in MySql?

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?

Upvotes: 0

Views: 7517

Answers (1)

cwallenpoole
cwallenpoole

Reputation: 82078

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.

Upvotes: 2

Related Questions