2011-06-15 103 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

相关问题