【问题标题】:INSERT INTO where some of the data is dependent on a selectINSERT INTO 某些数据依赖于选择的地方
【发布时间】:2013-09-29 17:25:42
【问题描述】:

我知道在所有输入数据已知时如何插入,并且我知道在所有数据都依赖于选择时如何插入,但我不知道如何在两者之间进行.我现在在哪里:

INSERT INTO takes (stu_id, "CS-001", 1, "Autumn", 2009, null)
VALUES (SELECT id AS stu_id
FROM student
WHERE dept_name = "Comp. Sci.")

因此我知道除了学生 ID 之外的所有其他输入数据,但是 MySQL 只是给了我一个语法错误。

【问题讨论】:

    标签: mysql sql select insert insert-into


    【解决方案1】:
    INSERT INTO takes (stu_id, col2, col3, col4, col5, col6) 
    SELECT id, 'CS-001', 1, 'Autumn', 2009, null
    FROM student 
    WHERE dept_name = 'Comp. Sci.'
    

    我不知道您的目标列名称 - 您必须用上面查询中的真实名称替换它们。

    【讨论】:

    • 这是我的第一次尝试,但它根本不起作用(即使它是 id 而不是 stu_id)。这是一个巨大的语法错误,错误代码为 1064
    • @user2171584:这将适用于目标表的正确列名。
    【解决方案2】:

    插入查询可以这样构造:

    insert into table
    (field1, field2, etc)
    (value1, value2 etc)
    

    或者像这样:

    insert into table
    (field1, field2, etc)
    select this, that, etc
    from etc
    

    您试图将两者结合起来。这就是您出错的原因之一。

    juergen 的回答是第二个构造的一个例子。他的这个和那个是字段和常量值的组合。这完全没问题。如果您遇到语法错误,则在您的详细信息中。他的回答显示了正确的总体思路。

    逐步构建您的查询通常是值得的。从这个开始:

    insert into takes
    (stu_id)
    select id
    from student
    where dept_name = 'Comp. Sci'
    

    如果可行,请在括号内添加一个字段以及适合查询的 select 子句的任何内容。继续这些小步骤,直到你做对了。这是我经常采用的方法。

    【讨论】:

      猜你喜欢
      • 2012-06-01
      • 2019-01-10
      • 1970-01-01
      • 2013-03-09
      • 1970-01-01
      • 2014-02-11
      • 2010-11-17
      • 2012-04-01
      • 2013-07-16
      相关资源
      最近更新 更多