简体   繁体   English

mysql中2列的唯一索引

[英]Unique index on 2 columns in mysql

I have one table in mysql named 'UserFriends' where I am updating my websites user's friends details. 我在mysql中有一个名为“ UserFriends”的表,用于更新网站用户的朋友详细信息。

here is the schema of the table (UserFriends) 这是表的架构(UserFriends)

id  int,
Userid int,
friendid int,
createdate timespan

now, I want to create unique index on userid & friendid. 现在,我想在userid和friendid上创建唯一索引。 that i have created unique index well. 我已经很好地创建了唯一索引。 so, right now i am not able to insert same userid and friendid as duplicate. 因此,现在我无法插入相同的userid和friendid作为重复项。 but if i am inserting same value in opposite field it accept without generating error. 但是,如果我在相反的字段中插入相同的值,它将接受而不会产生错误。

example : 例如:

insert into userfriends ( userid, friendid )
select 1, 2  --- insert perfect
insert into userfriends ( userid, friendid )
select 1, 2  --- show error because unique index comes in a picture

now i am inserting 现在我要插入

insert into userfriends ( userid, friendid )
select 2, 1  --- records insert here (i don't want this)

How do i prevent this? 我该如何预防?

First things first: for your inserts, don't use 'select' to generate the values, as it's liable to become confusing. 首先,第一件事:对于您的插入内容,请不要使用“选择”来生成值,因为这样很容易造成混淆。 Instead do it this way: 而是这样做:

INSERT INTO userfriends (userid, friendid) VALUES (1, 2)

That said, the only way to have a unique qualifier that works backwards too is to do it programmatically. 也就是说,拥有一个也可以向后工作的唯一限定符的唯一方法是以编程方式进行。 If you want to prevent x,y from being accepted, run SELECT * FROM userfriends WHERE userid = y AND friendid = x and if you get a result, reject the insert before it happens. 如果要防止x,y被接受,请运行SELECT * FROM userfriends WHERE userid = y AND friendid = x ,如果得到结果,请在插入之前拒绝插入。 If you don't, then insert into the table as normal, and your unique key will deny it from there on. 如果不这样做,则照常插入表中,并且您的唯一键会从此位置拒绝它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM