【问题标题】:Insert data into table with result from another select query使用另一个选择查询的结果将数据插入表中
【发布时间】:2011-09-15 07:08:01
【问题描述】:

我正在就以下问题寻求帮助: 我有两张桌子 Table_1 列是itemidlocationidquantity

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
)

【问题讨论】:

    标签: mysql select insert


    【解决方案1】:

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

    【讨论】:

    • 如果你有相同的列,这就足够了:insert into table_2 select itemid,quantity from table_1 where locationid=1
    【解决方案2】:
    INSERT INTO `test`.`product` ( `p1`, `p2`, `p3`) 
    SELECT sum(p1), sum(p2), sum(p3) 
    FROM `test`.`product`;
    

    【讨论】:

      【解决方案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"));
      

      【讨论】:

      • 欢迎来到 Stack Overflow。关于这个答案有两件事。 1)代码应该被格式化。缩进四个空格。 2) 最好解释一下为什么你的代码可以解决提问者的问题。
      猜你喜欢
      • 2022-01-26
      • 1970-01-01
      • 1970-01-01
      • 2021-02-25
      • 2014-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多