【发布时间】:2019-05-25 18:06:43
【问题描述】:
我有一个带有复合主键的 mysql 表,以及一个使用外键引用第一个的子表。
插入一行子表的正确语法是什么?
如何在插入语句中给出组合键的两个部分?
我有这些表;
CREATE TABLE IF NOT EXISTS parent (
p_id INT NOT NULL,
p_org INT NOT NULL,
PRIMARY KEY(p_id, p_org),
p_name VARCHAR(12))
ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS child (
c_id INT NOT NULL PRIMARY KEY,
c_org INT NOT NULL,
c_p_id INT NOT NULL, FOREIGN KEY(c_p_id, c_org) REFERENCES parent(p_id, p_org),
c_info VARCHAR(12))
ENGINE=InnoDB;
向父级插入两行后;
insert into parent values(100, 1, 'name-1'), (100, 2, 'name-2');
我想在 child 中插入一行。
insert into child values(1000, 2, 100, 'info-for-2');
但我不知道如何指定复合键。我想指定 (100 和 2) 而不是 100,以便我的子行仅使用 (100 2) 引用父行。
使用上面的插入语句,我的查询返回两行而不是一行;
select * from parent join child on c_p_id = p_id;
返回;
p_id p_org p_name c_id c_org c_p_id c_info
100 1 name-1 1000 2 100 info-for-2
100 2 name-2 1000 2 100 info-for-2
但想只获得 (100 2) 的行。
我真的必须在连接上指定 c_org 吗?
【问题讨论】:
标签: mysql sql foreign-keys sql-insert composite-primary-key