0

I have a relation table in Mysql with 3 columns

  1. ID (Primary key and Auto Increment)
  2. Ref_id1 (Reference ID from table1)
  3. Ref_id2 (Reference ID from table1 also)

How can i forbid, in database level, any pair combination of Ref_id1 and Ref_id2 from reappearing.

EDIT:

For example: After i insert a row like this

id Ref_id1 Ref_id2 1 1 2

i want to forbid ANY other row with the same pair of Ref_id1 and Ref_id2 (which a UNIQUE INDEX can solve) AND any row with the reversed pair

Ref_id1 Ref_id2 2 1

PS. Sorry for the ugly coding, i'm new to the community and i can't use the tools correctly

EDIT 2:

My question is different from the duplicate proposed because i want to be able to restrict BOTH insertions

Pair1:

Ref_id1 Ref_id2 1 2

AND

Pair2:

Ref_id1 Ref_id2 2 1

AFTER my original insertion.

EDIT 3:

If this helps at all: Both Ref_id1 and Ref_id2 are foreign keys from the same column of a foreign table

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Bill
  • 459
  • 1
  • 3
  • 13

1 Answers1

0

You want a unique key constraint.

In your Create Table syntax:

CREATE TABLE my_table(
  id bigint(20) primary key auto_increment,
  ref_id1 bigint(20) not null,
  ref_id2 bigint(20) not null,
  unique key `ref_uniqueness` (ref_id1, ref_id2)
)

Or, if your table already exists, use alter table:

ALTER TABLE my_table
ADD UNIQUE CONSTRAINT `ref_uniqueness` (ref_id1, ref_id2)
nasukkin
  • 2,460
  • 1
  • 12
  • 19
  • Is this going to solve both problems? – Bill Aug 05 '16 at 11:33
  • It doesn't work. I already had my table created so i used the second suggestion in MySQL workbench and it has syntax error near CONSTRAINT – Bill Aug 05 '16 at 11:43