ds2128629 2018-01-09 07:49
浏览 79
已采纳

SQL避免插入重复的新购物车ID

(First and foremost, sorry for my bad English, it is not my first language.)

I have a SQL database table to store some shopping cart, that likes something like this:

Shopcart
----------
ID(PK) shopcartid price user
1 S123 112.00 Tom
2 S124 6543.00 Mary
3 S125 456.00 James
4 S126 25.00 Peter

Since the database was not set by me, I don't have much knowledge with the internal designs, proprieties, etc.

As far as I know for the database design wise,
ID column,
Allow NULL: No
Type: int
(Is Identity): Yes
shopcartid column,
Allow NULL: No
Type: nvarchar(100)

There is also an clustered index set.
Name: PK_shopcart
Columns: ID(ASC),shopcartid(ASC)
Is Unique: Yes
Type: Primary Key

The website (in php) will create a shopping cart (INSERT INTO Shopcart shopcartid price user VALUES {new shopcartid} {price} {user}) once the user login to the site and if they don't already have a shopping cart assigned. What is a MUST is that the shopcartid to not duplicate. While ID is also unique, it should be auto-increment(?)(not sure). However, currently, the shopcartid keeps on duplicating as we add more shopping cart.

The way the site creates the shopcartid, originally was to use SELECT COUNT(*) AS value FROM Shopcart, and add 1 to the shopcartid, which most definitely don't work and will create duplicates.

What I proposed was to get the last shopcartid by getting the latest added shopping cart by ID which should be unique, and add 1 to that.:
SELECT shopcartid from Shopcart where ID = (SELECT MAX(ID) FROM Shopcart)

However, my colleague said it could still have possibility of creating duplicate shopcartid since with many concurrent users visiting the site, it could be possible that the fetch the same ID, thus the same shopcartid, and created a duplicated new shopcartid.

So here is my question, what is the best way to avoid creating a duplicate shopcartid, and how could this be achieved.

  • 写回答

2条回答 默认 最新

  • douhunkuang8955 2018-01-09 08:01
    关注

    Simply use a Sequencer for setting the ID of the shopping cart. Each time a user wants to create a new shopping cart, the sequenzer provides a new, unique ID.

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

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?