如何使 2 列协同工作以使其独一无二?

How to make 2 columns work together to be unique?

一个客户,cus_id可以拥有多栋房子。一个房子有一个 house_num 本身并不是唯一的。但是,cus_idhouse_num 一起是唯一的。我怎样才能使 cus_idhouse_num 在一起是唯一的。所以我可以使用 INSERT IGNORE INTO 而不必担心我会插入重复的

CREATE TABLE house(
    house_id                    int
                                NOT NULL
                                AUTO_INCREMENT
                                PRIMARY KEY,

    cus_id                      int
                                NOT NULL,
                                FOREIGN KEY (cus_id) REFERENCES customers (cus_id),

    house_num                   int
                                NOT NULL
);

table

的例子
+----------+--------+-----------+
| house_id | cus_id | house_num |
+----------+--------+-----------+
|        1 |      3 |         4 |
|        2 |      3 |         5 |
|        3 |      8 |         4 |
|        4 |      9 |         2 |
+----------+--------+-----------+

但是,该行不能存在,因为它会与 house_id 2

重复
+----------+--------+-----------+
|        5 |      3 |         5 |
+----------+--------+-----------+

尝试对 cus_idhouse_num 的组合添加唯一约束:

ALTER TABLE house ADD CONSTRAINT your_cnstr UNIQUE (cus_id, house_num);

在您的 CREATE 声明中,您可以尝试:

CREATE TABLE house (
    house_id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
    cus_id int NOT NULL FOREIGN KEY (cus_id) REFERENCES customers (cus_id),
    house_num int NOT NULL,
    CONSTRAINT your_cnstr UNIQUE (cus_id, house_num)
);