mysql怎么建立主键外键
mysql 实现设置多个主键的操作user表,身份证号码要唯一,手机号码,邮箱要唯一
实现方式:
表结构不用动。一个主键id 加索引实现
如图类型设置索引类型为unique 唯一 选择栏位,命个名就行。索引方式btree 就好。ok啦~
补充:mysql实现多表主键不重复
同一个数据库中有两张表,里面字段都是一样,只是因为存的数据要区分开。但是主键不能重复。具体实现如下:
新建数据库 mytest
新建user表和admin表
|
create table ` user ` ( `user_id` int (11) not null , `user_name` varchar (255) not null , ` password ` varchar (255) not null , `phone` varchar (255) not null , primary key (`user_id`) ) comment= '用户表' collate = 'utf8_general_ci' engine=innodb; |
|
create table `admin` ( `user_id` int (11) not null , `user_name` varchar (255) not null , ` password ` varchar (255) not null , `phone` varchar (255) not null , primary key (`user_id`) ) comment= '管理员表' collate = 'utf8_general_ci' engine=innodb; |
新建序列表:
|
create table ` sequence ` ( `seq_name` varchar (50) not null , `current_val` int (11) not null , `increment_val` int (11) not 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 (11) begin 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 (11) begin 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 > |
最终实现:
以上为个人经验,希望能给大家一个参考,也希望大家多多支持开心学习网。如有错误或未考虑完全的地方,望不吝赐教。
原文链接:https://blog.csdn.net/qq_39930369/article/details/86687285