I'm working on a database for shop items. I want these shop items to have IDs like 0001, 0002 etc. But if I use AUTO_INCREMENT
(which I need) it will go as 1, 2 etc. Is there any way to make AUTO_INCREMENT
for PRIMARY KEY
work this way because I need IDs to have a specific number of characters?
This is the code where I'm creating the items
table:
CREATE TABLE items (
item_id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(30) NOT NULL,
price FLOAT NOT NULL,
discount INT
);
This is the Python loop where I'm putting all items from .csv file into the database table:
for item in items_list:
mycursor.execute(f"INSERT INTO items(name, price, discount) VALUES (item['name'], item['price'], item['discount']);")
Is it possible to make AUTO_INCREMENT
work that way or I need to do it manually?
CodePudding user response:
Primary keys need to have one job only, that of uniquely identifying a row. As soon as you start trying to make them look presentable by formatting them or make them sequential without gaps, or even when you try to use them to see if one row was created before another, you create reasons to want to change them. Practically anything visible to users or involved in business logic is going to end up needing to change. And primary keys shouldn't change. Changing a primary key means deleting the row and making a new one with the new key value, and also fixing all the references to the old key. It's fiddly and error-prone, and is something you want to avoid.
Make a separate column for a user-visible identifier separate from the PK that you can have full control over. Don't use the PK for that.
CodePudding user response:
Auto_incrememts are tricky, because they can't be used in BEFORE INSERT TRIGGER it is alays 0
so you need another table and a AFTER INSERT TRIIGGER
CREATE TABLE items ( item_id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(30) NOT NULL, price DECIMAL(10,2) NOT NULL, discount INT );
CREATE TABLE t1 ( item_id_1 varchar(8) )
CREATE TRIGGER ins_sum AFTER INSERT ON items FOR EACH ROW INSERT INTO t1 VALUES(LPAD (NEW.item_id , 8, '0'));
INSERT INTO items (name,price, discount) VALUES ('test1',1.1,1)
INSERT INTO items (name,price, discount) VALUES ('test2',1.1,1)
INSERT INTO items (name,price, disc
SELECT * FROM t1
| item_id_1 | | :-------- | | 00000001 | | 00000002 | | 00000003 |
SELECT *,(SELECT item_id_1 FROM t1 WHERE item_id_1 0 = i.item_id) FROM items i
item_id | name | price | discount | (SELECT item_id_1 FROM t1 WHERE item_id_1 0 = i.item_id) ------: | :---- | ----: | -------: | :--------------------------------------------------------- 1 | test1 | 1.10 | 1 | 00000001 2 | test2 | 1.10 | 1 | 00000002 3 | test3 | 1.10 | 1 | 00000003
SELECT i.*,t1.item_id_1 FROM items i JOIN t1 ON i.item_id = t1.item_id_1 0
item_id | name | price | discount | item_id_1 ------: | :---- | ----: | -------: | :-------- 1 | test1 | 1.10 | 1 | 00000001 2 | test2 | 1.10 | 1 | 00000002 3 | test3 | 1.10 | 1 | 00000003
db<>fiddle here