MySQL中的多列外键?

MySQL中的多列外键?,mysql,Mysql,我有一个表,它的主键由两列组成(product\u id、attribute\u id)。我有另一个表需要引用此表。如何在另一个表中创建外键以将其链接到表中具有两个主键的行?一个表上只能有一个主键。事实上,可以包含多个字段并不会增加主键的数量,仍然有一个 由于PK对的一部分不是唯一的,因此您显然必须创建一个外键,该外键同时引用两个字段:引用t1(f1,f2)。类似的操作应该可以做到: CREATE TABLE MyReferencingTable AS ( [COLUMN DEFINITI

我有一个表,它的主键由两列组成(product\u id、attribute\u id)。我有另一个表需要引用此表。如何在另一个表中创建外键以将其链接到表中具有两个主键的行?

一个表上只能有一个主键。事实上,可以包含多个字段并不会增加主键的数量,仍然有一个


由于PK对的一部分不是唯一的,因此您显然必须创建一个外键,该外键同时引用两个字段:引用t1(f1,f2)。

类似的操作应该可以做到:

CREATE TABLE MyReferencingTable AS (
   [COLUMN DEFINITIONS]
   refcol1 INT NOT NULL,
   rofcol2 INT NOT NULL,
   CONSTRAINT fk_mrt_ot FOREIGN KEY (refcol1, refcol2)
                        REFERENCES OtherTable(col1, col2)
) ENGINE=InnoDB;
  • MySQL需要索引外键,因此索引在引用列上
  • 使用约束语法可以命名约束,以便在以后需要时更容易修改和删除
  • InnoDB执行外键,MyISAM不执行。(语法已解析但被忽略)

如果我们想要外键的逻辑,比如

FOREIGN KEY COmments(issue_id)
REFERENCES Bugs(issue_id) OR FeatureRequests(issue_id)
例如:

CREATE TABLE Issues (
issue_id int PRIMARY KEY,
status VARCHAR(20)

);




CREATE TABLE Comments (
comment_id int PRIMARY KEY,
issue_type VARCHAR(20), -- "Bugs" or "FeatureRequests"
issue_id BIGINT UNSIGNED NOT NULL,
comment TEXT
);



CREATE TABLE Bugs (
issue_id int PRIMARY KEY,
severity VARCHAR(20),
FOREIGN KEY (issue_id) REFERENCES Issues(issue_id)
);
CREATE TABLE FeatureRequests (
issue_id int PRIMARY KEY,
sponsor VARCHAR(50),
FOREIGN KEY (issue_id) REFERENCES Issues(issue_id)
);





INSERT INTO Issues VALUES(1,'ON'),(2,'ON'),(3,'OFF'),(6,'OFF'),(8,'ON');

INSERT INTO Comments VALUES(1,'Bugs',1,'A'),(2,'Bugs',3,'B'),(3,'Bugs',1,'C'),(4,'Bugs',3,'D'),(5 ,'FeatureRequests',8,'L'),
(6,'FeatureRequests',6,'W'),(7,'FeatureRequests',1,'ZX');



INSERT INTO Bugs VALUES(1,'severity_1'),(3,'severity_for_3');


INSERT INTO FeatureRequests VALUES(2,'sponsor_2_'),(8,'sponsor_for_8'),(1,'sponsor_for_1')
选择:

MariaDB [test]> SELECT * FROM Comments JOIN FeatureRequests  ON Comments.issue_i
d = FeatureRequests.issue_id AND Comments.issue_type= 'FeatureRequests';


MariaDB [test]> SELECT * FROM Comments JOIN Bugs  ON Comments.issue_id = Bugs.is
sue_id AND Comments.issue_type= 'Bugs';
+------------+------------+----------+---------+----------+----------------+
| comment_id | issue_type | issue_id | comment | issue_id | severity       |
+------------+------------+----------+---------+----------+----------------+
|          1 | Bugs       |        1 | A       |        1 | severity_1     |
|          2 | Bugs       |        3 | B       |        3 | severity_for_3 |
|          3 | Bugs       |        1 | C       |        1 | severity_1     |
|          4 | Bugs       |        3 | D       |        3 | severity_for_3 |
+------------+------------+----------+---------+----------+----------------+
4 rows in set (0.00 sec)

FWIW,MyISAM解析并忽略外键语法。自从MySQL 4.1.2以来,您不需要冗余地声明索引。另外,请确保这两个表都是InnoDB,因为正如Bill指出的,MyISAM不支持外键。由于显式索引,我两次被否决了?严厉的我确实指出了InnoDB是必要的。你说-
MySQL需要索引外键,因此引用列上的索引不应该是
引用列