开发者

Giving users unique ids in the form of an auto_increment

开发者 https://www.devze.com 2023-04-08 01:29 出处:网络
Let me explain, take an inventory system. You have items and you have rooms. If I have a table for items, that means everyone\'s data gets inserted into the same table. Hence, the primary key (item_id

Let me explain, take an inventory system. You have items and you have rooms. If I have a table for items, that means everyone's data gets inserted into the same table. Hence, the primary key (item_id) is auto_incremented by 1. So "John" signs up two weeks later and his first item's id might be 210. How can I go about giving each user their own "id?" Without resorting to creating their own table, which could get messy if I have 1,000 users.

| item_id | item_name | user_id |
|    1    |  sofa     |    1    |
|    2    |  ps3      |    1    |
|    3    |  ipad     |    1    |
|    4    |  laptop   |    2    |

Example URL:

http://domain.com/item/view/1

John would get a URL of http://domain.com/item/view/210 for his first item.

In case this helps someone else, here's what i ended up doing.

Create a mapping 开发者_开发知识库table. In my case, "users_items" with item_id and user_id and remove the primary key.

SELECT case when item_id IS NULL then isnull(max(item_id)+1) else max(item_id) +1 end as item_id 
    FROM users_items WHERE user_id = $user+id;


Maybe create an additional column item_code which you can populate with something like

SELECT ISNULL(MAX(item_code) + 1) FROM item
WHERE user_id = 2

Considering item_id is a surrogate key it shouldn't matter what value it is, the user has no concern about that, but item code can be the code for the user to display.


If its only about places where item id is visible to user, why not storing first item_id for each user in some column and then just adding desired ID(from URL, for example) to this number? For example in users table user with id=2 will have 4 as value of this column, and when he opens url /item/view/%X system will add (%x-1) to 4 and get real item_id.

0

精彩评论

暂无评论...
验证码 换一张
取 消