MySQL-使两列的组合唯一 [英] Mysql - Make combination of two columns unique

查看:188
本文介绍了MySQL-使两列的组合唯一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个mysql数据库表,其中有两个重要列,即 university_id 列和 username 列。 在这里,university_id对于整个表应该是唯一的,但是这两列可以重复很多次,但是相同的组合不能重复,用户名应该只对university_id唯一。这是我的意思

  id university_id用户名
1 10001 DrDre
2 10002 slimshady
3 10003 slimshady
4 10004 DrDre
5 10005 lilwyn
6 10005 lilwyn<-仅此行是非法的
7 10005 kanyeEast




  • 如果可能的话,我也想知道如何使用symfony2中的学说来做到这一点



-谢谢

解决方案

如果没有,请在alter语句下面使用对表进行任何约束-

 更改表mytable 
添加唯一键Uk_university_id(university_id),
添加唯一键Uk_unvid_username(university_id,用户名);

更新:

 更改表mytable 
添加唯一键Uk_unvid_username(university_id,username);


i have a mysql database table with two columns of importance, the university_id column and username column. Here the university_id should be unique to the whole table, but the two columns can repeat many times but the same combinations must not repeat, the username should be unique only to the university_id. here is what i mean

 id   university_id     username
 1       10001           DrDre
 2       10002          slimshady
 3       10003          slimshady
 4       10004           DrDre
 5       10005           lilwyn
 6       10005           lilwyn <- only this line would be illegal 
 7       10005          kanyeEast

  • if possible i would also like to know how to do it using doctrine in symfony2

-thanks

解决方案

use below alter statement if you did not make any constraint on table-

alter table mytable 
add unique key Uk_university_id(university_id), 
add unique key Uk_unvid_username(university_id,username);

Update:

alter table mytable  
add unique key Uk_unvid_username(university_id,username);

这篇关于MySQL-使两列的组合唯一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆