Run an UPDATE on Mysql only when the number of Rows is 1

Asked

Viewed 288 times

1

How to make a UPDATE only run when the number of Rows returned is 1 in a single query with SQL syntax only using the example below?

Example:

SELECT count(*) AS rows FROM exemplo WHERE id_usuario = 100;

if (rows == 1)
{
    //executar UPDATE
}
  • 1

    The table you want to update is the same whose number of Rows you need to check?

  • Yes and no. I need to use on 2 occasions in which one is in the same table and the other is not. Well thought out.

1 answer

0


CASE WHEN it seems to me the ideal here.

If the table you want to use be different of the table whose number of Rows you need to check can do something similar to this:

UPDATE tabela2 SET campo=
   CASE WHEN (SELECT count(*) FROM exemplo WHERE id_usuario=100) = 1 THEN 
     'novovalor' -- novo valor para "campo" 
   ELSE 
     campo -- atualiza "campo" com o valor de "campo", nada muda
END;

If the update target table is the same whose number of Rows should be checked the thing is more complicated since Mysql does some internal crazy that does not allow you to directly reference the same update table in the select query Inner, but it is still possible with a small trick:

UPDATE exemplo SET campo=
   CASE WHEN (SELECT count(*) FROM (
      SELECT * FROM exemplo WHERE id_usuario=100
   ) AS aliasqualquer) = 1 THEN 
     'novovalor' -- novo valor para "campo" 
   ELSE 
     campo -- atualiza "campo" com o valor de "campo", nada muda
END;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.