2016-07-23 146 views
-1

是否有可能這樣做?插入選擇不工作不知道爲什麼

insert into cart(cartid,rowid,productname) select max(cartid)+1 from cart, 2, "hello" 

我想插入我自己的rowid和產品名稱

+1

你是否錯過了選擇,即「SELECT MAX(cartid)+1,2,'hello'FROM cart' – Unoembre

回答

1

的值。這是你如何短語查詢:

insert into cart (cartid, rowid, productname) 
    select max(cartid) + 1, 2, 'hello' 
    from cart; 

然而,這是錯誤的方式有自動遞增cartid。相反,將列定義爲自動遞增,並簡單地執行:

insert into cart (rowid, productname) 
    select 2, 'hello' 
    from cart; 

數據庫自動處理分配。

+0

感謝它的工作!順便問一下,你知道這是否有效?我收到一個錯誤,說你不能申報2個表格。更新購物車設置productname ='hey'其中cartid =(從購物車中選擇max(cartid)) – Marcus

+0

MySQL不允許您在查詢中的大多數其他位置參考正在更新的表。 –

1

的語法不正確:

insert into cart(cartid,rowid,productname) 
select max(cartid)+1, 2, "hello" from cart 

的另一個問題是,如果車表是空的,那麼最大(cartid)將是無效和無法初始化表,所以你必須使用聚結:

insert into cart(cartid,rowid,productname) 
select coalesce(max(cartid)+1, 1), 2, "hello" from cart 

但爲什麼你想要做那樣的事情?你不能使用auto_increment列嗎?

+0

謝謝!嗯,它的複雜..我很樂意使用auto_increment,如果我可以太哈哈 – Marcus

相關問題