组合主键作为外键删除一组删除所有
composite primary key as foreign key deleting one set delets all
我有两个 table,其中一个有复合主键,另一个有外键。它们都设置为级联删除。问题是,当我删除时,假设从主 table 中删除了一个复合键集 "name: John date: 02.02.2018",所有 John 行都从 table 中删除了外键,但是可以有一个集合 "name: John date: 04.04.2018" 以及日期为 02.02.2018 的所有行也被删除我怎样才能删除只有外键集匹配的行?
更新:
CREATE TABLE messages (
session_date date NOT NULL,
chat int(11) NOT NULL,
message longtext NOT NULL,
date time NOT NULL,
receiver int(11) NOT NULL,
PRIMARY KEY (date,receiver),
KEY FK_messages_sessions (session_date,chat),
KEY FK_messages_sessions_2 (chat,session_date),
CONSTRAINT FK_messages_sessions
FOREIGN KEY (session_date)
REFERENCES sessions (session_date)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT FK_messages_sessions_2
FOREIGN KEY (chat)
REFERENCES sessions (chat)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1
您定义了两个外键而不是复合外键。
尝试:
CREATE TABLE `messages` (
`session_date` date NOT NULL,
`chat` int(11) NOT NULL,
`message` longtext NOT NULL,
`date` time NOT NULL,
`receiver` int(11) NOT NULL,
PRIMARY KEY (`date`,`receiver`),
KEY `FK_messages_sessions` (`session_date`,`chat`),
CONSTRAINT `FK_messages_sessions`
FOREIGN KEY (`session_date`, `chat`)
REFERENCES `sessions` (`session_date`, `chat`)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1
(session_date,chat)
也可以是 (chat,session_date)
,具体取决于引用的 table.
中定义的主键中这些列的顺序
我有两个 table,其中一个有复合主键,另一个有外键。它们都设置为级联删除。问题是,当我删除时,假设从主 table 中删除了一个复合键集 "name: John date: 02.02.2018",所有 John 行都从 table 中删除了外键,但是可以有一个集合 "name: John date: 04.04.2018" 以及日期为 02.02.2018 的所有行也被删除我怎样才能删除只有外键集匹配的行?
更新:
CREATE TABLE messages (
session_date date NOT NULL,
chat int(11) NOT NULL,
message longtext NOT NULL,
date time NOT NULL,
receiver int(11) NOT NULL,
PRIMARY KEY (date,receiver),
KEY FK_messages_sessions (session_date,chat),
KEY FK_messages_sessions_2 (chat,session_date),
CONSTRAINT FK_messages_sessions
FOREIGN KEY (session_date)
REFERENCES sessions (session_date)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT FK_messages_sessions_2
FOREIGN KEY (chat)
REFERENCES sessions (chat)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1
您定义了两个外键而不是复合外键。
尝试:
CREATE TABLE `messages` (
`session_date` date NOT NULL,
`chat` int(11) NOT NULL,
`message` longtext NOT NULL,
`date` time NOT NULL,
`receiver` int(11) NOT NULL,
PRIMARY KEY (`date`,`receiver`),
KEY `FK_messages_sessions` (`session_date`,`chat`),
CONSTRAINT `FK_messages_sessions`
FOREIGN KEY (`session_date`, `chat`)
REFERENCES `sessions` (`session_date`, `chat`)
ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1
(session_date,chat)
也可以是 (chat,session_date)
,具体取决于引用的 table.