perl-如果缺少列词则插入值

时间:2019-11-18 10:31:31

标签: mysql sql

在perl中,如果

,我想插入缺少的行
database 1                               database 2
-----------------------------------      ----------------------------------
table truc                               table truc2
-----------------------------------      ----------------------------------
   parti                                 id   parti missing_line
-----------------------------------     ----------------------------------
   MODEM                                14   MODEM   0
   EELV                                 33   EELV    0
   SP                                    2   SP      0
   CPNT                                  3   CPNT    0

5分钟后,我有了此信息,pati列中的SP和MODEM丢失了,如果列中的任何单词丢失,我想插入1:

database 1                               database 2
-----------------------------------      ----------------------------------
table truc                               table truc2
-----------------------------------      ----------------------------------
   parti                                id   parti missing_line
-----------------------------------     ----------------------------------
                                        14   MODEM   1
   EELV                                 33   EELV    0
                                         2   SP      1
   CPNT                                  3   CPNT    0

感谢您的答复,

我的perl和sql代码是here

2 个答案:

答案 0 :(得分:0)

看起来像这样的东西应该可以工作(但是我没有时间测试它):

UPDATE database2.truc2 t2
SET t2.missing_line = 1
WHERE t2.parti NOT IN
(SELECT t1.parti FROM database1.truc t1);

答案 1 :(得分:0)

您可以使用MySQL update ... join ... set ... where ...语法。使用left joinwhere ... is null,您可以识别不匹配的记录:

update database2.truc2 t2
left join database1.truc1 t2 on t2.parti = t1.parti
set t2.missing_line = 1
where t1.parti is null

另一种选择是使用not exists

update database2.truc2 t2
set t2.missing_line = 1
where not exists (
    select 1 from database1.truc1 t2 where t2.parti = t1.parti
)

我主张不要使用not in,它在处理null值时会产生意外的结果;如果子查询返回的任何值为null,则not in条件实际上成为传递(相当于1 = 1),这将导致源中的所有记录表正在更新。