简体   繁体   English

MySQL:如何通过链接到其他两个表的两个外键插入到表中?

[英]MySQL: how to insert into a table with two foreign keys linking to two other tables?

I have the following db structure with 3 tables as an example: 我有以下带有3个表的数据库结构作为示例:

Employee 雇员

  • id // primary key, autoincrement id //主键,自动递增
  • employee_no // a varchar employee_no //一个varchar

Scenario 脚本

  • id // primary key, autoincrement id //主键,自动递增
  • key // a varchar 键//一个varchar

Case 案件

  • id // primary key, auto-increment id //主键,自动递增
  • employee_id // foreign key to Employee table employee_id // Employee表的外键
  • scenario_id // foreign key to Scenario table scheme_id //方案表的外键

Say I already have data in employee and scenario table and I want to insert a new case into the case table so that it fills the foreign keys during the insert. 假设我在employee和scenario表中已经有数据,并且我想在案例表中插入一个新案例,以便在插入过程中填充外键。 The new case has employee_no in employee table and key in scenario table. 新案例在employee表中具有employee_no ,而在方案表中具有key I will need to join the two tables using the above values to get employee id and scenario id. 我将需要使用上述值将两个表连接起来以获取员工ID和方案ID。

This post ( Mysql: How to insert values in a table which has a foreign key ) showed how this can be done with one foreign key, how do I do the same thing with two foreign keys? 这篇文章( Mysql:如何在具有外键的表中插入值 )显示了如何使用一个外键来完成此操作,如何使用两个外键来完成相同的事情?

I currently have something like this that does not work: 我目前有这样的东西不起作用:

INSERT INTO `case` (scenario_id, employee_id, employee_no)
SELECT 
(SELECT scenario.id FROM scenario WHERE scenario.`key` = 'UC01') as scenario_id,
(SELECT employee.id, employee.employee_no FROM employee WHERE employee.employee_no = "0001") as employee_id, employee_no

Join the two tables: 连接两个表:

INSERT INTO case (scenario_id, employee_id)
SELECT s.id, e.id
FROM scenario AS s
CROSS JOIN emplopyee AS e
WHERE s.`key` = 'UC01'
AND e.employee_no = '0001'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM