2011-06-15 102 views
34

我尋求以下問題的幫助: 我有兩個表 Table_1itemidlocationidquantity將數據插入表與另一個選擇查詢結果

Table_2itemidlocation1location2location3

我想從Table_1(僅quantity列)複製數據到Table_2(到location1列)。 itemid在兩個表中都是相同的(Table_1有重複的項目ID),所以這就是我想要複製到新表並將每個位置的所有數量保留爲一列的原因。我使用下面的查詢,但它不工作

INSERT INTO 
Table_2(location1) 
(
SELECT qty 
FROM Table_1 
WHERE locationid = 1 AND Table_1.locationid = Table_2.locationid 
) 

回答

78

如果table_2是空的,那麼請嘗試以下插入語句:

insert into table_2 (itemid,location1) 
select itemid,quantity from table_1 where locationid=1 

如果table_2已經包含itemid值,然後再嘗試此更新聲明:

update table_2 set location1= 
(select quantity from table_1 where locationid=1 and table_1.itemid = table_2.itemid) 
+0

謝謝。試圖插入語句而不是更新語句。 – mmdel 2011-06-15 07:47:38

+0

謝謝,您的代碼有幫助 – Thoman 2015-09-08 18:52:31

+1

如果您有相同的列,就足夠了:'insert into table_2選擇itemid,數量from table_1 where locationid = 1' – Tarik 2018-03-07 22:40:32

0
INSERT INTO `test`.`product` (`p1`, `p2`, `p3`) 
SELECT sum(p1), sum(p2), sum(p3) 
FROM `test`.`product`; 
-2

下面是一個這樣一個查詢的例子:

INSERT INTO [93275].[93276].[93277].[93278] ([Mobile Number], [Mobile Series], [Full Name], [Full Address], [Active Date], company) IN 'I:\For Test\90-Mobile Series.accdb 
SELECT [1].[Mobile Number], [1].[Mobile Series], [1].[Full Name], [1].[Full Address], [1].[Active Date], [1].[Company Name] 
FROM 1 
WHERE ((([1].[Mobile Series])="93275" Or ([1].[Mobile Series])="93276")) OR ((([1].[Mobile Series])="93277"));OR ((([1].[Mobile Series])="93278")); 
+0

歡迎使用Stack Overflow。這件事上有兩件事。 1)代碼應該格式化。縮進四個空格。 2)最好解釋*爲什麼*你的代碼解決了提問者的問題。 – 2017-06-24 11:35:04

相關問題