INSERT ... SELECT(插入多行)

时间:2014-05-08 17:09:11

标签: mysql sql

我想将学者的id插入到tblinbox中。这是我的疑问:

    $sql = "INSERT INTO tblinbox VALUES ('','$sender','$type','$subject','$LRN','$content','$date', '$newyearLevel','','$userType','THIS_IS_FOR_THE_ID_OF_THE_SCHOLAR')
        SELECT id FROM tblscholar WHERE schoYear = '$newyearLevel'";

我的问题是,它没有插入。我的查询会改变什么?

4 个答案:

答案 0 :(得分:2)

INSERT ... SELECT语法不允许VALUES声明。值是从SELECT返回的结果。

请参阅此处的文档:http://dev.mysql.com/doc/refman/5.6/en/insert-select.html

老实说,我不完全确定你要插入的是什么。如果您尝试在tblscholar表中为每个id值插入变量中保存的相同值,那么您可能需要执行以下操作:

INSERT INTO tblinbox
/* 
   maybe add column definitions here to make it clearer
   column definitions could look like this:
    (
    someField,
    type,
    subject,
    LRN,
    content,
    `date`,
    newyearLevel,
    someOtherField,
    userType,
    id
    )
*/
SELECT
    '',
    '$sender',
    '$type',
    '$subject',
    '$LRN',
    '$content',
    '$date',
    '$newyearLevel',
    '',
    '$userType',
    id
FROM tblscholar
WHERE schoYear = '$newyearLevel'

答案 1 :(得分:0)

考虑到id是insert语句中的第一列,试试这个

$sql = "INSERT INTO tblinbox VALUES ((SELECT id FROM tblscholar WHERE schoYear = '$newyearLevel'),'$sender','$type','$subject','$LRN','$content','$date', '$newyearLevel','','$userType')";

答案 2 :(得分:0)

INSERT语句支持VALUES子句后跟一行值,或者SELECT查询支持列以匹配要插入的表的列。

但不是两个!

但您可以在SELECT查询中添加常量值:

$sql = "INSERT INTO tblinbox 
    SELECT '','$sender','$type','$subject','$LRN','$content','$date',
        '$newyearLevel','','$userType', id 
    FROM tblscholar WHERE schoYear = '$newyearLevel'";

答案 3 :(得分:0)

您可以插入值,从另一个表中提取值或提供值,如下所示:

方式1: INSERT INTO tblinbox(coloumn_name1,coloumn_name2)VALUES(value1,value2);

方式2: INSERT INTO tblinbox(coloumn_name1,coloumn_name2)SELECT value1,来自tblscholer的value2,其中schoYear =' $ newyearLevel';