douzhang5295 2015-06-27 11:34
浏览 232
已采纳

使用INSERT ... ON DUPLICATE KEY UPDATE和几个键

I have a DB in which I would like one of three keys (userId, udid and token) to identify the row: all three of them are unique keys and the first is also primary and autoincremental. Basically I would like to update all the values when one of the keys is the same. Unfortunately if I use:

INSERT INTO users (udid, nickname, playerID, `language`, app, token,
 `In Arrivo HD`) VALUES ('AB71C145-2FFE-4BA8-B0E7-9F121948C962', 'Fabry65', 'G:274138044', 'it_IT', 'In Arrivo HD', 
'605a383a7e3469a3da0b471cd5b73af7384ca5e389eeb7cd72e550e96f37f450', NOW()+ INTERVAL 1 YEAR) 
ON DUPLICATE KEY UPDATE udid='AB71C145-2FFE-4BA8-B0E7-9F121948C962', 
token='605a383a7e3469a3da0b471cd5b73af7384ca5e389eeb7cd72e550e96f37f450',  lastAccess=NOW(), active=1, nickname='Fabry65',  
playerID='G:274138044',`language`='it_IT', app='In Arrivo HD'

And the key to be repeated happens to be the token, I have error:

Duplicate entry '605a383a7e3469a3da0b471cd5b73af7384ca5e389eeb7cd72e550e96f37f450' for key 'token'

And the same would of course happen if it were the other the two other keys to be repeated. Chaining ON DUPLICATE KEY UPDATE's does not seem to work. How may I do it?

In brief my issue is updating a row if any of three keys are the same, and inset a new row if all of them are different.

  • 写回答

2条回答 默认 最新

  • douhunkuang8955 2015-06-27 14:31
    关注

    Ok, I think I found a solution:

    $query = "UPDATE users SET token='token', udid='$udid', lastAccess=NOW(), active=1, nickname='".$nickname."', playerID='".$playerID."',`language`='".$language."', app='".$app."' WHERE userId=$userId";
        $resultUpdate=$mysqli->query($query);
        if (!$resultUpdate){
            $query = "UPDATE users SET udid='$udid', lastAccess=NOW(), active=1, nickname='".$nickname."', playerID='".$playerID."',`language`='".$language."', app='".$app."' WHERE userId=$userId"
        }
    

    I execute the first query trying to also update the token, if it fails, it means the token is the same and so I update without mentioning the token.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵