MySQL 테이블 기본 키를 일부 접두사로 자동 증가시키는 방법
이런 테이블이 있어요
table
id Varchar(45) NOT NULL AUTO_INCREMENT PRIMARY KEY,
name CHAR(30) NOT NULL,
'LHPL001','LHPL002','LHPL003'... 등과 같이 내 ID 필드를 늘리고 싶습니다 . 어떻게해야합니까? 가능한 방법을 알려주십시오.
이것이 정말로 필요하다면 시퀀싱을위한 별도의 테이블과 트리거를 사용하여 목표를 달성 할 수 있습니다.
테이블
CREATE TABLE table1_seq
(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
);
CREATE TABLE table1
(
id VARCHAR(7) NOT NULL PRIMARY KEY DEFAULT '0', name VARCHAR(30)
);
이제 방아쇠
DELIMITER $$
CREATE TRIGGER tg_table1_insert
BEFORE INSERT ON table1
FOR EACH ROW
BEGIN
INSERT INTO table1_seq VALUES (NULL);
SET NEW.id = CONCAT('LHPL', LPAD(LAST_INSERT_ID(), 3, '0'));
END$$
DELIMITER ;
그런 다음 table1에 행을 삽입합니다.
INSERT INTO Table1 (name)
VALUES ('Jhon'), ('Mark');
그리고 당신은
| 아이디 | 이름 | ------------------ | LHPL001 | Jhon | | LHPL002 | 마크 |
다음은 SQLFiddle 데모입니다.
일반 숫자 auto_increment ID로 테이블을 생성하지만으로 정의 ZEROFILL하거나 LPAD선택할 때 0을 추가 하는 데 사용 합니다. 그런 다음 CONCAT원하는 행동을 얻기위한 값입니다. 예 1 :
create table so (
id int(3) unsigned zerofill not null auto_increment primary key,
name varchar(30) not null
);
insert into so set name = 'John';
insert into so set name = 'Mark';
select concat('LHPL', id) as id, name from so;
+---------+------+
| id | name |
+---------+------+
| LHPL001 | John |
| LHPL002 | Mark |
+---------+------+
예 2 :
create table so (
id int unsigned not null auto_increment primary key,
name varchar(30) not null
);
insert into so set name = 'John';
insert into so set name = 'Mark';
select concat('LHPL', LPAD(id, 3, 0)) as id, name from so;
+---------+------+
| id | name |
+---------+------+
| LHPL001 | John |
| LHPL002 | Mark |
+---------+------+
I know it is late but I just want to share on what I have done for this. I'm not allowed to add another table or trigger so I need to generate it in a single query upon insert. For your case, can you try this query.
CREATE TABLE YOURTABLE(
IDNUMBER VARCHAR(7) NOT NULL PRIMARY KEY,
ENAME VARCHAR(30) not null
);
Perform a select and use this select query and save to the parameter @IDNUMBER
(SELECT IFNULL
(CONCAT('LHPL',LPAD(
(SUBSTRING_INDEX
(MAX(`IDNUMBER`), 'LHPL',-1) + 1), 5, '0')), 'LHPL001')
AS 'IDNUMBER' FROM YOURTABLE ORDER BY `IDNUMBER` ASC)
And then Insert query will be :
INSERT INTO YOURTABLE(IDNUMBER, ENAME) VALUES
(@IDNUMBER, 'EMPLOYEE NAME');
The result will be the same as the other answer but the difference is, you will not need to create another table or trigger. I hope that I can help someone that have a same case as mine.
'Nice programing' 카테고리의 다른 글
| Amazon CloudFront는 내 S3 웹 사이트 버킷의 index.html 규칙을 존중하지 않습니다. (0) | 2020.11.20 |
|---|---|
| 테스트 생성, 시도 생성, 생성 캐치 중 가장 바람직한 디자인은 무엇입니까? (0) | 2020.11.20 |
| ng-mouseover를 누르고 angularjs에서 마우스를 사용하여 항목을 토글합니다. (0) | 2020.11.20 |
| Julia는 동적으로 입력됩니까? (0) | 2020.11.20 |
| foreach ()는 참조로 반복합니까? (0) | 2020.11.20 |