› MySQL 5.5 Community Server
› MySQL 5.6 Community Server
› Percona Configuration Wizard
› XtraBackup 搭建主从复制
Great Sites on MySQL
› Percona
› MySQL Performance Blog
› Severalnines
推荐管理工具
› Sequel Pro
› phpMyAdmin
推荐书目
› MySQL Cookbook
MySQL 相关项目
› MariaDB
› Drizzle
参考文档
› http://mysql-python.sourceforge.net/MySQLdb.html
yagamil
V2EX  ›  MySQL

请教 mysql 插入或更新某个字段的写法

  •  
  •   yagamil · Apr 8, 2024 · 2445 views
    This topic created in 909 days ago, the information mentioned may be changed or developed.
    请教 db 大佬,要更新某一行的某个字段,比如 让 totalSale 字段+X, 如果不存在这行数据的时候插入整条数据,totalSale 值为 X 。

    问 chatGPT 需要知道唯一键的 id 才能做到,但更新的那行记录是通过条件查找到的,有大佬知道怎么操作么?

    逻辑大概这样
    if(`select 1 from xxx where xxxx`){
    // 存在,直接更新
    `update xxx set totalSale = totalSale + X where month=xx and user=xxx`
    }else{
    `insert into xxx (xxx)`
    }
    5 replies  •  2024-04-08 14:37:58 +08:00
    justseemore
        1
    justseemore  
       Apr 8, 2024   ❤️ 1
    insert into on duplatekey 关键字
    waitingChou
        2
    waitingChou  
       Apr 8, 2024   ❤️ 1
    直接 replace 或者 on duplicate key update

    没理解你的疑惑,你插入数据的时候不也要组装那个 唯一键的 id 信息么。
    wuyiccc
        3
    wuyiccc  
       Apr 8, 2024
    乐观锁+全局 redis 分布式锁解决一切并发问题
    yagamil
        4
    yagamil  
    OP
       Apr 8, 2024
    @zpfhbyx @waitingChou 感谢大佬
    jalena
        5
    jalena  
       Apr 8, 2024
    @zpfhbyx
    @waitingChou

    只要有约束,以上 2 种方式都行,但 replace 方式是先删除再创建。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   753 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 19:36 · PVG 03:36 · LAX 12:36 · JFK 15:36
    ♥ Do have faith in what you're doing.