2011-06-10 102 views
1

我試過按照建議here的語法,但它不適用於我的查詢。我可以在INSERT查詢中使用SELECT子查詢嗎?

這是我目前有:

INSERT INTO dot (entrant_id, year, entry_code, title, retail_category, campaign_type, client_company, client_city, client_state, field_date_active, height, width, depth, weight, oversize_fee, volt_110, attach_to_gridwall, hang_from_ceiling, table_or_countertop, misc_setup, created_date, modified_date, co_entrant) 
     VALUES (288, 2011, 1234, 'RG Total Defense BW mixed Floorstand', '32', 'C', 'Henkel', 'Scottsdale', 'AZ', '2011-01-15', 60, 26, 15, 29, 0, '0', '0', '0', '0', '', NOW(), NOW(), '') 

不過,我需要entry_code的值從同一個表中選擇 - 我能做到這一點作爲一個單獨的查詢:

MAX(entry_code) FROM dot WHERE year = 2011 

但似乎無法將其與插入語句集成在一起。這可能嗎?或者像這樣的子查詢只有在從另一個表中選擇時才能工作?

+0

你能否澄清「不工作」的意思。例如記錄不會插入沒有和錯誤。沒有插入錯誤,語法錯誤等。 – 2011-06-10 16:11:39

+0

可能只是你的問題中的一個錯字,但它應該讀取'SELECT MAX ... WHERE year ='2011'' – bdares 2011-06-10 16:12:07

+0

@dbares:year是一個int列;你不需要單引號。 – EmmyS 2011-06-10 16:44:07

回答

2
INSERT INTO dot (entrant_id, year, entry_code, ...) 
SELECT 288, 2011, MAX(entry_code), ... FROM dot WHERE year=2011 
+0

你是說所有其他插入值後的where子句應該在最後?喜歡這個? 'INSERT INTO dot(entrant_id,year,entry_code,...) SELECT 288,2011,MAX(entry_code),'NatureSweet and Build a Better Burger','32','M','NatureSweet','San Antonio ','TX','2011-05-15',22 \「,22 \」,0,0,0,'0','0','0','0','請參閱附件pdf 'NOW(),NOW(),'' FROM dot WHERE year = 2011' – EmmyS 2011-06-10 16:47:57

+0

因爲這給了我一個很大的舊錯誤:#1064 - 你的SQL語法錯誤;檢查與您的MySQL服務器版本相對應的手冊,以找到正確的語法以在'..)附近使用SELECT 288,2011,MAX(entry_code),'NatureSweet and Build A Better Burger','at line 1 – EmmyS 2011-06-10 16:49:11

+1

您是否替換了' ...'與實際名稱的字段名稱? (我只是使用'...'來節省我的答案空間。) – 2011-06-10 16:56:38

0

您提供的鏈接中的語法應該可以工作。但是,這不是你「目前有」嘗試這樣的語法的語法(這是相當類似的鏈接。):

insert into dot(field1, field2, field3, field4) select max(entry_code), 'value2', val3, 'value4' from dot where year = 2011 
0
INSERT INTO dot (entrant_id, year, entry_code, title, retail_category, campaign_type, client_company, client_city, client_state, field_date_active, height, width, depth, weight, oversize_fee, volt_110, attach_to_gridwall, hang_from_ceiling, table_or_countertop, misc_setup, created_date, modified_date, co_entrant) 
VALUES (288, 2011, (SELECT MAX(entry_code) FROM dot WHERE year = 2011), 'RG Total Defense BW mixed Floorstand', '32', 'C', 'Henkel' ... 
相關問題