使用另一个选择查询的结果将数据插入表中

时间:2011-06-15 06:56:02

标签: mysql select insert

我正在寻求以下问题的帮助: 我有两张桌子 Table_1itemidlocationidquantity

Table_2列为itemidlocation1location2location3

我想将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
)

3 个答案:

答案 0 :(得分:94)

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

答案 1 :(得分:0)

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

答案 2 :(得分:-3)

以下是此类查询的示例:

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