1

我想要一对(tag1,tag2)和tag_id之间的双射。

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?
     );

我不想参考,例如:

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

换句话说,我希望 REFERENCE 从(tag1,tag2)到标签(tag_id)是唯一的,而不是唯一的(tag1,tag2)。

4

1 回答 1

3

这可能更像您正在寻找的内容:

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)
);

将“tag_id”作为主键意味着您只能拥有一个具有给定“tag_id”的条目,并且基于“tag_id”的搜索会很快。

'question_id' 上的索引将基于 'question_id' 提高搜索速度,我认为这是您尝试使用原始 PRIMARY KEY 定义所做的事情。如果您真的希望 (tag_id, question_id) 对是唯一的,就像您拥有的那样,那么在其中添加一个 UNIQUE (tag_id, question_id) ,但我会说您应该将 tag_id 作为主键。

The uniqueness constraint on (tag1, tag2) prevents the reverse mapping from having duplicates.

Here are a few examples of what can work:

Works:

1 -> (x, y)

2 -> (x, z)

Fails (tag_id is a primary key, and therefore is unique):

1 -> (x, y)

1 -> (y, x)

Fails (the pair (tag1, tag2) is not unique):

1 -> (x, y)

2 -> (x, y)

However, the pair (x, y) is not equal to the pair (y, x). I'm not sure how to catch that uniqueness constraint.

于 2009-08-17T18:12:33.640 回答