MySQL insert statement (insert into table (columns

2019-04-12 02:05发布

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 )

4条回答
何必那么认真
2楼-- · 2019-04-12 02:13

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

查看更多
Deceive 欺骗
3楼-- · 2019-04-12 02:26

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.

查看更多
Explosion°爆炸
4楼-- · 2019-04-12 02:33

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)
)
查看更多
放荡不羁爱自由
5楼-- · 2019-04-12 02:37

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
查看更多
登录 后发表回答