问题描述
我有两个MySQL表之间有一对多的关系。例如: CREATE TABLE test1(
pk1 INTEGER AUTO_INCREMENT PRIMARY KEY,
testvalue1 INTEGER
);
CREATE TABLE test2(
pk2 INTEGER AUTO_INCREMENT PRIMARY KEY,
testvalue2 VARCHAR(50),
fk2 INTEGER NOT NULL,
FOREIGN KEY(fk2)参考test1(pk1)
);
如果我想在两个表中插入记录,我可以先在PK表中插入一个记录(例如确定PK值(例如 SELECT MAX(pk1)AS LastId FROM test1
)INSERT INTO test1 SET testvalue1 = 100 或使用 LAST_INSERT_ID()
)
,最后使用该值填充第二个表中的FK列。
但是有可能在1命令/查询/动作中实现这一切吗?那么让我们使用AUTO INCREMENTs来填充PK和FK值?
你应该使用两个INSERT命令;或尝试使用INSERT触发器。
编辑:
一个触发器的例子:
CREATE TABLE dept(
id INT(11)NOT NULL AUTO_INCREMENT,
dept_name VARCHAR(255)DEFAULT NULL,
PRIMARY KEY(id)
)
ENGINE = INNODB;
CREATE TABLE emp(
id INT(11)NOT NULL AUTO_INCREMENT,
emp_name VARCHAR(255)DEFAULT NULL,
dept_id INT(11)DEFAULT NULL,
PRIMARY KEY(id),
CONSTRAINT FK_emp_dept_id FOREIGN KEY(dept_id)
参考dept(id)ON DELETE RESTRICT ON UPDATE RESTRICT
)
ENGINE = INNODB;
DELIMITER $$
CREATE TRIGGER trigger1
AFTER INSERT
ON dept
为每个ROW
BEGIN
INSERT INTO emp VALUES(NULL,Someone,NEW.id);
END
$$
DELIMITER;
- 尝试添加新的部门。
INSERT INTO dept VALUES(NULL,'Sales');
- 是否有新的默认员工?
SELECT * FROM emp;
+ ---- + ---------- + --------- +
| id | emp_name | dept_id |
+ ---- + ---------- + --------- +
| 1 |有人| 1 |
+ ---- + ---------- + --------- +
I have two MySQL tables with an one-to-many relationship between them. For example:
CREATE TABLE test1 (
pk1 INTEGER AUTO_INCREMENT PRIMARY KEY,
testvalue1 INTEGER
);
CREATE TABLE test2 (
pk2 INTEGER AUTO_INCREMENT PRIMARY KEY,
testvalue2 VARCHAR(50),
fk2 INTEGER NOT NULL,
FOREIGN KEY (fk2) REFERENCES test1 (pk1)
);
If I want to insert records in both tables I can first insert a record in the PK table (e.g. INSERT INTO test1 SET testvalue1=100
), determine the PK value (e.g. SELECT MAX(pk1) AS LastId FROM test1
or use LAST_INSERT_ID()
)and finally use that value to fill the FK column in the second table.
But is it possible to achieve this all in 1 command/query/action? So let's MySQL fill in the PK- and FK-values using the AUTO INCREMENTs?
You should use two INSERT commands; or try to use an INSERT-trigger.
EDIT:
--An example with trigger:
CREATE TABLE dept(
id INT(11) NOT NULL AUTO_INCREMENT,
dept_name VARCHAR(255) DEFAULT NULL,
PRIMARY KEY (id)
)
ENGINE = INNODB;
CREATE TABLE emp(
id INT(11) NOT NULL AUTO_INCREMENT,
emp_name VARCHAR(255) DEFAULT NULL,
dept_id INT(11) DEFAULT NULL,
PRIMARY KEY (id),
CONSTRAINT FK_emp_dept_id FOREIGN KEY (dept_id)
REFERENCES dept (id) ON DELETE RESTRICT ON UPDATE RESTRICT
)
ENGINE = INNODB;
DELIMITER $$
CREATE TRIGGER trigger1
AFTER INSERT
ON dept
FOR EACH ROW
BEGIN
INSERT INTO emp VALUES (NULL, 'Someone', NEW.id);
END
$$
DELIMITER ;
-- Try to add new department.
INSERT INTO dept VALUES(NULL, 'Sales');
-- Is there new default employee?
SELECT * FROM emp;
+----+----------+---------+
| id | emp_name | dept_id |
+----+----------+---------+
| 1 | Someone | 1 |
+----+----------+---------+
这篇关于填写MySQL在一个操作中记录一对多相关的表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!