温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在mysql中设置多个主键

发布时间:2021-02-07 18:19:46 阅读:1470 作者:Leah 栏目:开发技术
亿速云mysql数据库,读写分离,安全稳定,弹性扩容,低至0.3元/天!! 点击查看>>

本篇文章给大家分享的是有关怎么在mysql中设置多个主键,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

实现方式:

表结构不用动。一个主键Id 加索引实现

怎么在mysql中设置多个主键

如图类型设置索引类型为Unique 唯一 选择栏位,命个名就行。索引方式btree 就好。ok啦~

补充:mysql实现多表主键不重复

同一个数据库中有两张表,里面字段都是一样,只是因为存的数据要区分开。但是主键不能重复。具体实现如下:

新建数据库 mytest

新建user表和admin表

CREATE TABLE `user` (
 `user_id` INT(11NOT NULL,
 `user_name` VARCHAR(255NOT NULL,
 `password` VARCHAR(255NOT NULL,
 `phone` VARCHAR(255NOT NULL,
 PRIMARY KEY (`user_id`)
)
COMMENT='用户表'
COLLATE='utf8_general_ci'
ENGINE=InnoDB;
CREATE TABLE `admin` (
 `user_id` INT(11NOT NULL,
 `user_name` VARCHAR(255NOT NULL,
 `password` VARCHAR(255NOT NULL,
 `phone` VARCHAR(255NOT NULL,
 PRIMARY KEY (`user_id`)
)
COMMENT='管理员表'
COLLATE='utf8_general_ci'
ENGINE=InnoDB;

新建序列表:

CREATE TABLE `sequence` (
 `seq_name` VARCHAR(50NOT NULL,
 `current_val` INT(11NOT NULL,
 `increment_val` INT(11NOT NULL DEFAULT '1',
 PRIMARY KEY (`seq_name`)
)
COMMENT='序列表'
COLLATE='utf8_general_ci'
ENGINE=InnoDB;

新增一个序列:

INSERT INTO sequence VALUES ('seq_test''0''1');

创建currval函数,用于获取序列当前值:

delimiter #
create function currval(v_seq_name VARCHAR(50)) 
returns integer(11begin
 declare value integer;
 set value = 0;
 select current_val into value from sequence where seq_name = v_seq_name;
 return value;
end;

查询当前值:

select currval('seq_test');

创建nextval函数,用于获取序列下一个值:

delimiter #
create function nextval (v_seq_name VARCHAR(50)) returns integer(11begin
 update sequence set current_val = current_val + increment_val where seq_name = v_seq_name;
 return currval(v_seq_name);
end;

查询下一个值

select nextval('seq_test');

具体实现:

<insert id="addUser" parameterType="User">
  <selectKey keyProperty="userId" resultType="int" order="BEFORE">
   select nextval('seq_test');
  </selectKey>
  insert into user(user_id,user_name,password,phone) values
  (#{userId},#{userName, jdbcType=VARCHAR},#{password, jdbcType=VARCHAR}, #{phone, jdbcType=VARCHAR})
 </insert>
<insert id="addAdmin" parameterType="Admin">
  <selectKey keyProperty="userId" resultType="int" order="BEFORE">
   select nextval('seq_test');
  </selectKey>
  insert into admin(user_id,user_name,password,phone) values
  (#{userId},#{userName, jdbcType=VARCHAR},#{password, jdbcType=VARCHAR}, #{phone, jdbcType=VARCHAR})
 </insert>

最终实现:

怎么在mysql中设置多个主键

怎么在mysql中设置多个主键

以上就是怎么在mysql中设置多个主键,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

亿速云「云数据库 MySQL」免部署即开即用,比自行安装部署数据库高出1倍以上的性能,双节点冗余防止单节点故障,数据自动定期备份随时恢复。点击查看>>

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI

开发者交流群×