views:

344

answers:

3

I want to make a table that simply has two integer columns to serve as a mapping table between two different data sets and I wish to put the correct constraints on it.

I initially set the two columns as a compound primary key, but then realized that represents a many to many, only keeping duplicate many to many mappings from occurring.

How do I specify I want both columns to be unique integers in all rows? I'm using MS SQL, but I suppose this is a general database design question.

A: 

Use a UNIQUE column constraint on each column.

Doug Currie
+1  A: 

Create a Primary Key on one column and another separate unique constraint or unique index, on the other.

CREATE TABLE [dbo].[test](
    [x] [int] NOT NULL,
    [y] [int] NOT NULL,
     CONSTRAINT [PK_test] PRIMARY KEY CLUSTERED 
     ( [x] ASC) 
     WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, 
         IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, 
         ALLOW_PAGE_LOCKS  = ON) 
     ON [PRIMARY]) 
 ON [PRIMARY]

CREATE UNIQUE NONCLUSTERED INDEX [IX_test] ON [dbo].[test] 
  ([y] ASC) 
   WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, 
         SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, 
         DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, 
         ALLOW_PAGE_LOCKS  = ON)  
 ON [PRIMARY]
Charles Bretana
+2  A: 

Creating another table is done to create a many to many relationship, so you probably shouldn't have created it (unless I am missing something).

One to one mandatory is the same as having the two tables as a single table. The only acceptable one to one is optional, and you simply have to relate the two tables, no third table necessary.

Otávio Décio
unless the additional table is being created as a de-normalization to enhance performance. If, for example, this mapping table will be hit by queries 1000x/second, whereas the core table it is one-to-one with is very wide and will be hit only a few times per day...
Charles Bretana
Sure, but that can be achieved by some DBMS's through partitioning.
Otávio Décio
yes, this is referred to as vertical (or is it horizontal?) partitioning. and whether or not the DBMS has special capabilities to do this, you can manually so it by creating another one-to-one table from a subset of teh tables' attributes
Charles Bretana