Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
557 views
in Technique[技术] by (71.8m points)

sql - Unique constraint on combination of two columns?

I have been trying to figure out if it is possible to have a unique constraint for a combination of two columns.

Specifically I have two columns A and B.

I have a row like below

A     B
1     2

Then I want the following combinations to fail when inserted

A     B
1     2
2     1

I have tried adding a simple constraint

ALTER TABLE test ADD CONSTRAINT test_constraint UNIQUE (a, b);

but this lets me insert (2, 1) when (1, 2) already exists.

Is this possible to do? Or will I have to check if the combination exists before I insert?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can do this using an index on expressions:

create unique index unq_test_a_b on (test(least(a, b), greatest(a, b));

I don't think the unique constraint allows expressions (and don't have a convenient Postgres to test on right now), but this is essentially the same thing.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...