Mysql in PHP - how to update only one row in table but with greatest id number

前端 未结 9 2031

I am trying to update fields in my DB, but got stuck with such a simple problem: I want to update just one row in the table with the biggest id number. I would do something like

相关标签:
9条回答
  • 2021-02-19 03:54

    I have to update a table with consecutive numbers.

    This is how i do.


    UPDATE pos_facturaciondian fdu 
                SET fdu.idfacturacompra = '".$resultado["afectados"]."', 
                fdu.fechacreacion = '".$fechacreacion."'
                WHERE idfacturaciondian = 
                (
                    SELECT min(idfacturaciondian) FROM 
                    (   
                        SELECT * 
                        FROM pos_facturaciondian fds
                        WHERE fds.idfacturacompra = ''
                        ORDER BY fds.idfacturaciondian
                    ) as idfacturaciondian
                )
    
    0 讨论(0)
  • 2021-02-19 03:56

    We can update the record using max() function and maybe it will help for you.

     UPDATE MainTable
     SET [Date] = GETDATE()
     where [ID] = (SELECT MAX([ID]) FROM MainTable)
    

    It will work the perfect for me.

    0 讨论(0)
  • 2021-02-19 03:58

    I think iblue's method is probably your best bet; but another solution might be to set the result as a variable, then use that variable in your UPDATE statement.

    SET @max = (SELECT max(`id`) FROM `table`);
    UPDATE `table` SET `name` = "FOO" WHERE `id` = @max;
    

    This could come in handy if you're expecting to be running multiple queries with the same ID, but its not really ideal to run two queries if you're only performing one update operation.

    0 讨论(0)
提交回复
热议问题