V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
? 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 · 27 天前 · 1012 次点击
    请教 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 条回复  ?  2024-04-08 14:37:58 +08:00
    zpfhbyx
        1
    zpfhbyx  
       27 天前   ?? 1
    insert into on duplatekey 关键字
    waitingChou
        2
    waitingChou  
       27 天前   ?? 1
    直接 replace 或者 on duplicate key update

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

    只要有约束,以上 2 种方式都行,但 replace 方式是先删除再创建。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2443 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 10:25 · PVG 18:25 · LAX 03:25 · JFK 06:25
    Developed with CodeLauncher
    ? Do have faith in what you're doing.


    http://www.vxiaotou.com