开发者

SQL - How can I apply a "semi-unique" constraint?

I have a (simplified) table consisting of three columns:

id INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
foreignID INT NOT NULL,
name VARCHAR NOT NULL

Basically, I would like to add a constraint (at the database level rather than at the application level) where it only possible for one unique 'name' to exist per foreignID. For example, given the data (id, foreignid, name):

1,1,Name1
2,1,Name2
3,1,Name3
4,2,Name1
5,2,Name2

I want the constraint to fail if the user tries to insert another 'Name3' under 开发者_运维知识库foreignId 1, but succeed if the user tries to insert 'Name3' under foreignId 2. For this reason I cannot simply make the whole column UNIQUE.

I am having difficulty coming up with a SQL expression to achieve this, can anybody help me?

Thanks


Add a unique constraint on (ForeignID, Name). The exact syntax for that depends on your DBMS. For SQL Server:

CREATE UNIQUE INDEX IndexName ON YourTable (ForeignID, Name)

(The terms "unique constraint", "unique key" and "unique index" mean roughly the same.)


create a composite (multiple - column ) key... on those two columns

Create Unique Index MyIndexName On TableName(ForeignID, Name)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜