【问题标题】:Insert query issue- with foreign key插入查询问题 - 使用外键
【发布时间】:2012-11-09 03:45:39
【问题描述】:

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

我正在构建一个 java 应用程序并陷入使用外键插入的场景之一。假设我有 2 个表 Employee_TypeEmployee

Employee_Type |标识类型 |职位 | | -------- | -------------- | | 1|经理|

员工

empId EmpName emp_type

FK (emp_type) reference Employee_type(idType)

Employee_Type
1,
中的现在值 经理

我正在手动插入 Employee

INSERT INTO
   employee (empId, name, emp_type) 
VALUES
   (
      10, 'prashant', 1
   )

在上面的插入中,我手动插入 emp_type ,即 FK 。我的问题,有没有办法像下面的例子一样使用 select 自动插入 FK 值?

INSERT INTO
   employee(empId, name, emp_type) 
VALUES
   (
      10, 'prashant', 
      (
         SELECT
            idType 
         FROM
            Employee_type,
            employee 
         WHERE
            employee.emp_type = employee_type.idtype
      )
   )

【问题讨论】:

    标签: sql sql-insert


    【解决方案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 语句匹配的每一行插入一行。

    【讨论】:

    • 谢谢迈克尔...我正在使用 SQLite DB 和 ibatis
    • 我上面的语法对 SQLite 有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多