2009-08-17 20 views
1

Ich möchte eine Bijektion zwischen dem Paar (Tag1, Tag2) und Tag_id.Postgres: Eindeutige Referenz von A nach B

CREATE TABLE tags (
     question_id INTEGER NOT NULL, 
     tag_id SERIAL NOT NULL, 
     tag1 VARCHAR(20), 
     tag2 VARCHAR(20), 
     PRIMARY KEY(question_id, tag_id), 
     (tag1, tag2) UNIQUE references tags(tag_id)   #How? 
    ); 

Ich möchte keinen Hinweis wie:

(PHP, Perl) points to 1 and 2, 
3 points to (C#, null) and (Python, Elinks) 

Mit anderen Worten, ich möchte den Verweis aus (tag1, tag2) eindeutig sein TO-Tags (tag_id), nicht UNIQUE (tag1, tag2).

Antwort

3

Dies könnte mehr wie das, was Sie suchen:

CREATE TABLE tags (
    question_id INTEGER NOT NULL, 
    tag_id SERIAL NOT NULL, 
    tag1 VARCHAR(20), 
    tag2 VARCHAR(20), 
    PRIMARY KEY (tag_id), 
    INDEX (question_id), 
    UNIQUE (tag1, tag2) 
); 

machen ‚tag_id‘ der Primärschlüssel bedeutet, dass Sie nur einen Eintrag mit einer bestimmten ‚tag_id‘ haben können, und dass Durchsuchungen auf der Grundlage " tag_id 'wird schnell sein.

Der Index für 'question_id' verbessert die Suchgeschwindigkeit basierend auf 'question_id', was ich mit der ursprünglichen PRIMARY KEY-Definition zu tun glaube. Wenn Sie wirklich möchten, dass das Paar (tag_id, question_id) eindeutig ist, wie Sie es hatten, fügen Sie ein UNIQUE (tag_id, question_id) hinzu, aber ich würde sagen, dass Sie tag_id als Primärschlüssel belassen sollten.

Die Eindeutigkeitseinschränkung für (tag1, tag2) verhindert, dass die umgekehrte Zuordnung Duplikate enthält.

Hier sind ein paar Beispiele dafür, was funktionieren kann:

Works:

1 -> (x, y)

2 -> (x, z)

schlägt fehl (tag_id ein Primärschlüssel ist, und daher ist einzigartig):

1 -> (x, y)

1 - > (Y, x)

schlägt fehl (das Paar (TAG1, tag2) ist nicht eindeutig):

1 -> (x, y)

2 -> (x, y)

Allerdings ist das Paar (x, y) nicht gleich dem Paar (y, x). Ich bin mir nicht sicher, wie ich diese Eindeutigkeitsbeschränkung erfassen soll.

+0

Tippfehler? "Works: 1 -> (x, y) 2 -> (x, y)", "Fails (das Paar (tag1, tag2) ist nicht eindeutig): 1 -> (x, y) 2 -> (x, y) " –

+0

Danke, ich habe es entsprechend aktualisiert und die Formatierung korrigiert. – Jonathan

Verwandte Themen