使用外键插入查询问题

时间:2012-11-09 03:45:39

标签: sql

我是SQL新手。需要你们的帮助:))

我正在构建一个java应用程序并卡在其中一个scenerio中,用于插入foregign键。假设我有2个表 Employee_Type和Employee

Table **Employee_Type**
idType,
position

Table **Employee**----
empId,
EmpName,
emp_type 
FK (emp_type) reference Employee_type(idType)

Now values in **Employee_Type**
1,
Manager

I am inserting manually into Employee Table
insert into **employee** (empId,name,**emp_type**) values (10,'prashant',1)

Here in above insert i am inserting manually **emp_type** which is **FK** . My question, is there any way to insert FK value automatically using select like below example

insert into **employee** (empId,name,emp_type) values (10,'prashant',**(select idType from Employee_type,employee where employee.emp_type=employee_type.idtype))**

Please suggest.

1 个答案:

答案 0 :(得分:1)

您没有指定RDBMS,因此语法可能不同,但您应该能够重构语句以使用INSERT INTO ... SELECT格式的文字值:

INSERT INTO employee (empId,name,emp_type) 
  SELECT 
    /* Build a SELECT statement which includes the static values as literals */
    '10' AS empId,
    'prashant' AS name,
    /* and the idType column */
    idType
  FROM Employee_type,employee 
  WHERE employee.emp_type=employee_type.idtype

请注意,WHERE子句中没有任何其他内容,上面的内容会为employee语句中匹配的每一行SELECT插入一行。