Question

Create Table as follows where column1 and column2 are both foreign key values.

ID|Column1|Column2|

0 | 1 | 1

1 | 1 | 2

2 | 1 | 2

3 | 2 | 2

I don's want duplicates as with row id #2 when I insert.

I thought I could insert as so:

INSERT INTO tablename (column1, column2) VALUES (@last_id_in_col1key,@last_id_in_column2key) <*>

Then I want something like this:

<*> where column1 and column2 are not equal to @last_id_in_col1key and @last_id_in_column2key

Is there a way to add this to my table or does it have to be a seperate command?

alter table tablename add unique index(column1, column2);
Was it helpful?

Solution

It seems you're creating a so-called join table, for which the purpose is to relate items in table1 to items in table2 many to many.

This is usually done with a two-column table. The two columns in that table are both part of the primary key. You'd do this like so:

CREATE TABLE JoinTable ( 
   first_id  INT NOT NULL , 
   second_id INT NOT NULL , 

   PRIMARY KEY (first_id, second_id),

   FOREIGN KEY (first_id) 
    REFERENCES first(first_id)
    ON DELETE CASCADE,

   FOREIGN KEY (second_id) 
    REFERENCES second(second_id)
    ON DELETE CASCADE
 )

Wnen you do this, you won't be able to insert duplicate values.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top