Multiple Updates in MySQL

前端 未结 17 1039
南方客
南方客 2020-11-22 01:31

I know that you can insert multiple rows at once, is there a way to update multiple rows at once (as in, in one query) in MySQL?

Edit: For example I have the followi

17条回答
  •  無奈伤痛
    2020-11-22 01:33

    There is a setting you can alter called 'multi statement' that disables MySQL's 'safety mechanism' implemented to prevent (more than one) injection command. Typical to MySQL's 'brilliant' implementation, it also prevents user from doing efficient queries.

    Here (http://dev.mysql.com/doc/refman/5.1/en/mysql-set-server-option.html) is some info on the C implementation of the setting.

    If you're using PHP, you can use mysqli to do multi statements (I think php has shipped with mysqli for a while now)

    $con = new mysqli('localhost','user1','password','my_database');
    $query = "Update MyTable SET col1='some value' WHERE id=1 LIMIT 1;";
    $query .= "UPDATE MyTable SET col1='other value' WHERE id=2 LIMIT 1;";
    //etc
    $con->multi_query($query);
    $con->close();
    

    Hope that helps.

提交回复
热议问题