我有一组由 id 定义的点,以及一个定义这些点之间的连接的数据库表:
[第一点,第二点]
现在我可以强制 point1 和 point2 的排列是唯一的。所以只有 1 个条目,其中 point1 = x 和 point2 = y。但我想要独特的组合,这意味着如果有 point1 = x 和 point2 = y 的条目,则不可能获得 point1 的条目= y 和 point2 = x。
是否可以为此配置表格,还是我必须通过代码强制执行此操作?
最佳答案
也许这个结构应该适合你?
正确
--
-- Table structure for table `points`
--
CREATE TABLE IF NOT EXISTS `points` (
`point1` int(11) NOT NULL,
`point2` int(11) NOT NULL,
UNIQUE KEY `point1_point2_ux` (`point1`,`point2`),
UNIQUE KEY `point2_point1_ux` (`point2`,`point1`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
--
-- Triggers `points`
--
DROP TRIGGER IF EXISTS `testpoints`;
DELIMITER //
CREATE TRIGGER `testpoints` BEFORE INSERT ON `points`
FOR EACH ROW BEGIN
DECLARE num INTEGER DEFAULT 0;
DECLARE point INTEGER DEFAULT NULL;
SELECT count(*) INTO num FROM points WHERE point2 = NEW.point1 AND point1 = NEW.point2;
IF(num>0) THEN
SET point = NEW.point1;
SET NEW.point1 = NEW.point2;
SET NEW.point2 = point;
END IF;
END
//
DELIMITER ;
关于mysql - 如何在 MySQL 中强制执行两个相似字段的唯一组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6767298/