MySQL插入语句(插入表(列)select语句)

时间:2011-10-10 07:54:28

标签: mysql select insert

我正在尝试将值插入到表的选定列中,但只插入MySQL语句的结果。 select语句本身可以正常工作并返回结果。

与insert语句结合使用时,

失败
error incorrect syntax near `dedspgoods`.`case number`.

任何人都可以用正确的语法帮助我吗?我的错误语法如下:

insert into despgoods_alldetails 
  (`case number`, weight, customer, transporttypename) 
values 
( select despgoods.`case number`
       , despgoods.weight
       , despgoods.customer
       , customers.transporttypename 
  from despgoods 
    inner join customers 
      on despgoods.customer = customers.customer )

4 个答案:

答案 0 :(得分:19)

如果这是有效的SELECT

select despgoods.`case number`
     , despgoods.weight
     , despgoods.customer
     , customers.transporttypename 
from despgoods 
  inner join customers 
    on despgoods.customer = customers.customer

然后尝试这个(如果要插入VALUES的结果集,请注意没有SELECT子句:

insert into despgoods_alldetails 
  (`case number`, weight, customer, transporttypename) 
select despgoods.`case number`
     , despgoods.weight
     , despgoods.customer
     , customers.transporttypename 
from despgoods 
  inner join customers 
    on despgoods.customer = customers.customer

答案 1 :(得分:3)

正如@EdHeal所述,你需要在引号或反引号之间加上case number,因为列名中有一个空格(CASE是一个保留字的事实实际上只是一个有趣的细节,但在这种情况下,这不是打破查询的原因。)

insert into despgoods_alldetails (`case number`,weight,customer,transporttypename) 
values (
    select despgoods.`case number`, despgoods.weight, despgoods.customer, customers.transporttypename
    from despgoods 
    inner join customers on (despgoods.customer=customers.customer)
)

答案 2 :(得分:2)

case是保留字。需要在报价中加上“案例编号”。

答案 3 :(得分:1)

在这里

 INSERT INTO despgoods_alldetails(
                                  casenumber,
                                  weight,
                                  customer,
                                  transporttyplename)


 VALUES(SELECT desp.casenumber,
        desp.weight,
        despgoods.customer, 
        customers.transporttypename)

 FROM despgoods
 INNER JOIN customers on despgoods.customer = customers.customer

那里。应该工作正常。请记住,不要用空格命名变量,因为它可能变得非常棘手。我认为你在案例编号中有一个错误,因为它在两者之间有一个空格,当case是MySQL中的一个函数时。如果您还有其他需要,请告诉我。