doushi6947 2013-06-20 13:13
浏览 179

MySql - 避免更新时出现重复记录

I have the following update query which runs when a user logs in to their account having place items in their cart prior to logging in (a temporary account set up on the table)...

UPDATE cart_items SET account_id=$account WHERE account_id=$cookieId;

This occasionally creates duplicate results looking something like this:

id | account_id | itemNumber | itemQuantity
------------------------------------------
20 | 10         | 6          | 2
25 | 10         | 6          | 1

What I would like to do i write a query which avoids creating these duplicate records and just leaves a single record like this:

id | account_id | itemNumber | itemQuantity
------------------------------------------
20 | 10         | 6          | 3

I think using DUPLICATE KEY UPDATE might be what I'm looking for but I can't get my head around it. Can anyone help me out please?

  • 写回答

2条回答 默认 最新

  • duandang6352 2013-06-20 13:45
    关注

    || Updated ||

    Let's assume that you have a non-logged in user with the temporary id 15 and that he has ordered 2 items with itemNumber 6:

    id | account_id | itemNumber | itemQuantity
    ------------------------------------------
    20 | 15         | 6          | 2
    

    The temporary id is stored in the variable $cookieId, which has value 15. Now let's assume that this user logs into his account with id stored in $account, with the value 10.

    As a part of the log-in process you want to perform your query:

    UPDATE cart_items SET account_id=$account WHERE account_id=$cookieId;
    

    (Even though prepared statements should be something you would want to take a look at).

    The entry should now look like this:

    id | account_id | itemNumber | itemQuantity
    ------------------------------------------
    20 | 10         | 6          | 2
    

    Now let's assume that user 10 wants to buy 1 more item 6, then it would make most sense to

    SELECT * FROM cart_items WHERE account_id = $account AND itemNumber = $itemNumber; // $itemNumber is 6
    

    If the query returns true, then you

    UPDATE cart_items SET itemQuantity = itemQuantity+$numerOfItemsInOrder WHERE $account = $account AND itemNumber = $itemNumber; // $itemNumber is 6
    

    , you insert otherwise.

    You definitely don't want to update the account_id if the user logs out, only when he logs in.

    评论

报告相同问题?

悬赏问题

  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)
  • ¥20 怎么在stm32门禁成品上增加查询记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面
  • ¥50 NT4.0系统 STOP:0X0000007B
  • ¥15 想问一下stata17中这段代码哪里有问题呀
  • ¥15 flink cdc无法实时同步mysql数据
  • ¥100 有人会搭建GPT-J-6B框架吗?有偿