我最近问了this问题。
I have a relational database with three tables. The first containts id's that relate to the second. The second contains id's that relate to the third. The third contains the results I am after.
是否可以通过一个查询来 在第一个表中查询一个id 给出第三张表的所有结果 与它有关吗?
我选择的解决方案是:
select * from table1 t1 join table2 t2 on t1.t2ref = t2.id join table3 t3 on t2.t3ref = t3.id
Add a where clause to search for certain rows in table1
where t1.field = 'value'
我的新问题是:
我意识到我也需要插入到三个表中。我正在处理的是一个预订系统。是否可以编写一个查询,在查询后直接插入三个表(使用连接?)。
我的另一个考虑是我是否应该使用事务来确保同时运行两个查询...两者都发现 id 是“未保留的”然后导致重复预订或者是否有更简单的方法?
最佳答案
您绝对应该在一个事务中执行这三个插入操作。我可能会编写一个存储过程来处理插入。
编辑:
这是一个带有事务的存储过程示例。请注意使用 LAST_INSERT_ID() 来获取先前插入的记录的 ID。这只是两个表,但您应该能够将其扩展到三个表。
DELIMITER //
CREATE PROCEDURE new_engineer_with_task(
first CHAR(35), last CHAR(35), email CHAR(255), tool_id INT)
BEGIN
START TRANSACTION;
INSERT INTO engineers (firstname, lastname, email)
VALUES(first, last, email);
INSERT INTO tasks (engineer_id, tool_id)
VALUES(LAST_INSERT_ID(), tool_id);
COMMIT;
END//
DELIMITER ;
你这样调用它:
CALL new_engineer_with_task('Jerry', 'Fernholz', 'me@somewhere.com', 1);
关于mySQL - 插入三个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1723232/