【发布时间】:2022-10-07 14:38:08
【问题描述】:
我有这两张桌子:
CREATE TABLE `locations`(
`location_id` INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`location_id`)
);
CREATE TABLE IF NOT EXISTS `routes`(
`route_id` INT NOT NULL AUTO_INCREMENT,
`location_id_1` INT NOT NULL,
`location_id_2` INT NOT NULL,
FOREIGN KEY (`location_id_1`)
REFERENCES `locations` (`location_id`)
ON UPDATE CASCADE
ON DELETE CASCADE,
FOREIGN KEY (`location_id_2`)
REFERENCES `locations` (`location_id`)
ON UPDATE CASCADE
ON DELETE CASCADE,
UNIQUE KEY(`location_id_1`, `location_id_2`),
PRIMARY KEY (`route_id`)
);
我想在routes 表上是否有以下记录:
+---------------+---------------+
| location_id_1 | location_id_2 |
+---------------+---------------+
| 1 | 2 |
+---------------+---------------+
那么下面的记录不应该被允许:
+---------------+---------------+
| location_id_1 | location_id_2 |
+---------------+---------------+
| 2 | 1 |
+---------------+---------------+
请让我知道如何解决这个问题,即使这意味着我必须重组我的表格
-
是什么导致不允许第二条记录?任一列中是否存在 1 或 2?或两者? (1,2) 与 (2,1) 不同,因此如果有额外的上下文可能会有所帮助,尤其是在 uhm 表上进行架构重组的情况下。 :)
-
如果已经在任一列上设置了 1 和 2 的组合,则不应在后面的记录中允许它。
-
解决方案 1 - 功能唯一索引。解决方案 2 - 如果 value1 > value2,则交换值的唯一索引和触发器。解决方案 3 - 唯一索引 + CHECK 约束。还有更多解决方案...