2011-10-10 202 views
3

我試圖插入值到選定的表中的列,但只插入MySQL語句的結果。 select語句本身正確工作並返回結果。MySQL插入語句(插入到表(列)選擇語句)

當用INSERT語句是合併失敗,

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

誰能幫助我正確的語法?我erronous語法如下:

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) 
+0

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

,如果你要插入的結果集的SELECT的那麼試試這個(通知沒有VALUES條款SELECT的作用是什麼? –

+0

作品的選擇是: – Smudger

+0

選擇'despgoods'.case編號,'despgoods'.'weight','despgoods'.'c ustomer','customers'.'transporttypename' from despgoods inner join customers on despgoods.'customer' ='customers'.'customer') – Smudger

回答

15

如果這是工作的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 
+0

嗨@ypercube。非常感謝,語法完美。 apprecaite的幫助。 – Smudger

+0

只需注意,使用'INSERT INTO' ** ** **可以使用具有行列表**或** SELECT'列表的'VALUES'。 –

+0

並嘗試在表或列名稱中沒有空格。你可以使用'case_number'或'CaseNumber'。它使得它更容易,因爲您不必每次都重新引用它。 –

2

case是一個保留字。需要將「案例編號」放在引號中。

+0

嗨,我插入''在字段周圍,格式不包括在我提交評論時 – Smudger

+0

@Ryan:嘗試編輯你的問題。將代碼粘貼到您的問題中,然後選擇它並點擊**代碼**圖標:**'{}'**。這會將代碼格式化爲代碼。 –

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數是個錯誤,因爲它之間有一個空格,case是MySQL中的一個函數。需要幫助請叫我。

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) 
)