开发者

MySQL insert statement (insert into table (columns) select statement)

I am trying to insert values into selected columns of table, but only insert the results of a MySQL statement. the select statement works correctly by itself and returns the results.

when combined with the insert statement it is fails with

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

Can anyone assist me with the correct syntax? my erronous syntax 开发者_如何学编程is as below:

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 )


If this is the SELECT that works:

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

Then try this (notice there is no VALUES clause if you want to insert the result set of a 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


As stated by @EdHeal, you'll need to enclose case number between quotes or backticks as there is a space in the column name (the fact that CASE is a reserved word is actually only an interesting detail, but that's not what breaks the query in this 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)
)


case is a reserved word. Need to put 'case number' in quotes.


here it goes

 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

there. that should work fine. Remember, do not name your variables with spaces, because it can get real tricky. I think you had an error in case number because it has a space in between, when case is a function in MySQL. Let me know if you need anything else.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜