mysql+多列外键_MySQL中的多列外键?
如果我們想要外鍵的邏輯,像這樣
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)
總結
以上是生活随笔為你收集整理的mysql+多列外键_MySQL中的多列外键?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 随机数的深究
- 下一篇: python中dump与dumps的区别