Home  >  Q&A  >  body text

mysql 怎么做到update只更新一行数据?


UPDATE quan.hexiao_code SET sort_code='LKUHFS' WHERE sort_code='SAMQLF';

这句话的where部分有两条记录,我只想修改其中一条,该怎么写?

黄舟黄舟2743 days ago767

reply all(2)I'll reply

  • 高洛峰

    高洛峰2017-04-17 15:27:20

    UPDATE quan.hexiao_code SET sort_code='LKUHFS' WHERE sort_code='SAMQLF' limit 1;

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-17 15:27:20

    I don’t know why the poster has such a problem. Shouldn’t each piece of data in the database be an independent piece and have its own characteristics? So when you WHERE sort_code='SAMQLF' it obviously means updating all matching data. If you only update one item, which one do you update? Should it have its features, so you should add this features.
    If you are so willful and want to randomly update the matching record, my solution is to randomly find the ID of a record in sort_code='SAMQLF' and use the ID to update the record.


    I just saw @shuhai's answer. Thank you for letting me know that there is such a grammar. I am not good at it - - |||
    Using UPDATE LIMIT 1 can indeed solve the original poster's problem. However, I still recommend that the poster should make it clear, such as only updating the matching one with the largest ID UPDATE quan.hexiao_code SET sort_code='LKUHFS' WHERE sort_code='SAMQLF' ORDER BY id DESC LIMIT 1

    reply
    0
  • Cancelreply