dongqufi82315 2014-02-20 11:06
浏览 45
已采纳

Mysql:更新全部或首次选择和更新后?

I have a table with 2 column: id and count. Count is exclusive OR (only one of them can be 1 at same time). I need to update a row with count = 1 and need to put the previous count 1 at 0.

I think two strategies:

1) Do a select on the table, find the row at 1. Update it at 0. Update the row that i want be at 1.

2) Global update the table at count 0. Update the row that i want be at 1.

In the first case i do 3 query but "small". In the second case i do 2 query but one of them is "big".

Which strategy is better?

  • 写回答

1条回答 默认 最新

  • duanan5940 2014-02-20 11:19
    关注

    If you are simply swapping the value on two rows you could do it in a single query.

    eg.

    +----+-------+
    | id | count |
    +----+-------+
    | 1  | 0     |
    | 2  | 0     |
    | 3  | 1     |
    +----+-------+
    

    Update using a self join:

    update myTable a, myTable b set
        a.`count` = b.`count`,
        b.`count` = a.`count`
    where a.id = '2'
    and b.id = '3'
    

    The result:

    +----+-------+
    | id | count |
    +----+-------+
    | 1  | 0     |
    | 2  | 1     |
    | 3  | 0     |
    +----+-------+
    

    If you want to target a specific row, you can do that also. eg. row with id 1 should have a count of 1, and whatever currently has a count of 1 should be reset back to 0.

    update myTable a, myTable b set
        a.`count` = 1,
        b.`count` = 0
    where a.id = '1'
    and b.`count` = '1'
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元