>  기사  >  데이터 베이스  >  MySQL에서 시퀀스 시퀀스를 사용하는 방법 요약

MySQL에서 시퀀스 시퀀스를 사용하는 방법 요약

WBOY
WBOY앞으로
2022-09-13 18:01:453012검색

추천 학습: mysql 비디오 튜토리얼

오라클 데이터베이스에서 지속적으로 자체 증가하는 데이터 유형 값을 원하는 경우 시퀀스를 생성할 수 있습니다. MySQL 데이터베이스에는 시퀀스가 ​​없습니다. 일반적으로 테이블에 자동 증가 열이 하나만 필요한 경우 MySQL의 auto_increment를 사용할 수 있습니다(테이블에는 자동 증가 기본 키가 하나만 있을 수 있음). Oracle과 같은 MySQL에서 시퀀스를 사용하려면 어떻게 해야 합니까?

예를 들어 다음과 같은 테이블 정의가 있습니다.

create table `t_user`(
    `id` bigint auto_increment primary key,
    `user_id` bigint unique comment '用户ID',
    `user_name` varchar(10) not null default '' comment '用户名'
);

여기서 user_id에는 자동 증가, 순서 및 고유성이 필요합니다. 조건에 맞는 값을 얻기 위해서는 Snowflake 알고리즘, Redis나 Zookeeper 등을 사용하는 등 다양한 구현 방법이 있으므로 여기서는 하나씩 소개하지 않겠습니다. 여기에서는 MySQL의 auto_increment 및 last_insert_id()를 사용하여 Oracle과 유사한 시퀀스를 구현하는 방법을 소개합니다.

방법 1. 저장 프로시저 사용

1. 자동 증가 기본 키가 포함된 간단한 테이블을 만듭니다.

예제는 다음과 같습니다.

create table `t_user_id_sequence` (
    `id` bigint not null auto_increment primary key,
    `t_text` varchar(5) not null default '' comment 'insert value'
);

2. 저장 프로시저 만들기

delimiter &&
create procedure `pro_user_id_seq` (out sequence bigint)
begin
    insert into t_user_id_sequence (t_text) values ('a');
    select last_insert_id() into sequence from dual;
    delete from t_user_id_sequence;
end &&
delimiter ;

3.Test

call pro_user_id_seq(@value);
select @value from dual;

저장 프로시저를 사용하려면 저장 프로시저를 한 번 호출한 후 값을 할당해야 하는데 조금 번거롭습니다.

방법 2. 함수 사용

1. 시퀀스를 생성하는 함수 만들기

delimiter &&
create function user_id_seq_func() returns bigint
begin
    declare sequence bigint;
    insert into t_user_id_sequence (t_text) values ('a');
    select last_insert_id() into sequence from dual;
    delete from t_user_id_sequence;
    return sequence;
end &&
delimiter ;

2. Test

select user_id_seq_func() from dual;
 
insert into t_user (user_id, user_name) values (user_id_seq_func(), 'java');
select * from t_user;

추천 학습: mysql 동영상 튜토리얼

위 내용은 MySQL에서 시퀀스 시퀀스를 사용하는 방법 요약의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 jb51.net에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제