SQL插入(从中选择)

时间:2014-11-20 02:34:49

标签: mysql sql

表1

ID             Qty      completed_qty   KEY
1              2          1              a
2              3          1              b
3              4          3              c

表2

ID             Qty      completed_qty   Percent     Priority         KEY
 1              2            1            50          H               a
 2              3            1           33.33        L               b
 3              4            3            75          H               c

我有2个表,我选择表1,然后使用下面的脚本插入表2

INSERT into table2(Qty, Completed_qty, Percent, KEY)
select Qty, Completed_qty, (completed_qty / Qty) * 100 [Percent], KEY from table1 where
KEY not in (select table2.KEY from table2)

因此,每次执行脚本时,相同的记录都不会复制到table2中 当table1的百分比发生变化时我遇到问题,我想更新表2中的百分比,我更改脚本如下但不能成功。

INSERT into table2(Qty, Completed_qty, Percent, KEY)
select Qty, Completed_qty, (completed_qty / Qty) * 100 [Percent], KEY from table1 where 
KEY not in (select table2.KEY from table2)
and (completed_qty / Qty) * 100 <> (select table2.Percent from table2)

我收到如下错误:

子查询返回的值超过1。子查询遵循=,!=,&lt;,&lt; =,&gt;,&gt; =或子查询用作表达式时不允许这样做

任何人之前都做过类似的剧本。知道我怎么能这样做吗?

4 个答案:

答案 0 :(得分:0)

这是您的查询:

insert into table2(Qty, Completed_qty, Percent, KEY)
    select Qty, Completed_qty, (completed_qty / Qty) * 100 [Percent], KEY
    from table1
    where KEY not in (select table2.KEY from table2) and
          (completed_qty / Qty) * 100 <> (select table2.Percent from table2)
-----------------------------------------^

第二个子查询是问题所在。我怀疑你想要not in

insert into table2(Qty, Completed_qty, Percent, KEY)
    select Qty, Completed_qty, (completed_qty / Qty) * 100 [Percent], KEY
    from table1
    where KEY not in (select table2.KEY from table2) and
          (completed_qty / Qty) * 100 not in (select table2.Percent from table2 where table2.Percent is not null)

使用is not null时,额外的not in非常重要。否则,NULL中的table2.Percent值将会过滤掉每一行。

答案 1 :(得分:0)

您可以在那里使用NOT IN条款

and (completed_qty / Qty) * 100 NOT IN (select table2.Percent from table2)

修改

您可以在NULL列中插入Percent,如下所示

INSERT into table2(Qty, Completed_qty, Percent, KEY)
select Qty, 
Completed_qty, 
null, 
KEY 
from table1 
where KEY not in (select table2.KEY from table2)

稍后再做UPDATE

UPDATE table2 a 
    JOIN table1 b ON a.key = b.key 
SET a.Percent = (b.completed_qty / b.Qty) * 100
WHERE a.Percent IS NULL

答案 2 :(得分:0)

您收到错误是因为子查询返回了多个结果。您可以使用NOT IN代替<>

但是,根据您的陈述I want update also the Percent in table 2。如果table2发生更改并且密钥已存在于table1中,您似乎想要更新table2。在这种情况下,您需要使用UPDATE查询:

UPDATE table2 t2
JOIN table1 t1 on t2.key = t1.key
SET Percent = t1.completed_qty / t1.Qty * 100 

答案 3 :(得分:0)

如果表中有很多行,则查询速度会很慢。

试试这个:

Insert into table2(Qty, Completed_qty, Percent, KEY)
Select a.Qty, a.Completed_qty, (a.completed_qty / a.Qty) * 100 [Percent], a.KEY 
From table1 a
Left Join table2 b On b.KEY = a.KEY
Where b.KEY is Null
    Or
    ( b.KEY is Not Null and ((a.completed_qty / a.Qty) * 100) <> b.Percent )