优化MySQL查询以进行更新?

时间:2017-07-24 14:19:17

标签: mysql

我有两个相同数据库的表说D,两个表是T1和T2。 T1具有属性a1,a2 ...... an和t2具有属性a1,a2。我想要一个查询,只有当T1.a1 = T2.a1时才能更新T1的值,并且只能在T1中插入T1。实施例:

enter image description here

enter image description here

3 个答案:

答案 0 :(得分:0)

选项

您至少有三个选择:

  • 删除镜像表,然后运行create as select以重新创建表
  • 使用mysql replace into语法(请参阅:Replace Into Query Syntax
  • 将您的问题拆分为两个查询:一次更新和一次插入查询

要遵循的例子和细节......

创建为选择

drop table t1;
create table t1 as select * from t2;

替换为

将t1.a1和t2.a1设置为两个表的主键。 运行:

Replace into t1(a1,a2) select a1, a2 from t2;

使用更新和插入:

UPDATE t1
INNER JOIN t2 ON t1.a1 = t2.a1
SET t1.a2 = t2.a2 where t1.a1 = t2.a1;

insert into t1(a1, a2) select a1, s2 from t2 where t2.a1 not in (select a1 from t1);

答案 1 :(得分:0)

您可以尝试以下内容:

INSERT INTO T1 (you columns list) VALUES (here select your values from T2 with restriction) ON DUPLICATE KEY UPDATE `a2`=values(`a2`)

答案 2 :(得分:0)

这是我理解问题的答案。如果这不是你想要的,也许你可以澄清一下。在问题中,a1和a2看起来像表中的字段。然而,在您的输出期望中,它们看起来像另一列的值。

insert t1(a1,a2,a3)
select t2.a1,t2.a2,t2.a3 from t2
left join t1 on t1.a1 = t2.a2
where t1.a1 is null

update t1
set t1.a1 = t2.a1, t1.a2 = t2.a2, t1.a3 = t2.a3
from t1 inner join t2 on t1.a1 = t2.a2

/*
    table data before record changes
    t1
    a1         a2         a3
    ---------- ---------- ----------
    bar        foo        fizz
    yin        yang       zen
    vidi       vini       vici
    lug        lag        lugger
    dig        dug        digger
    zoom       zimm       zammy
    riki       tiki       tavi
    yuz        wuz        wiz
    bip        bap        boop
    zip        zap        zing
    ding       aling      aling


    t2
    a1         a2         a3
    ---------- ---------- ----------
    foo        bar        fizz
    yuz        wuz        wiz
    vini       vidi       vici
    bip        bap        boop
    zip        zap        zing
    ding       aling      aling
    zimm       zoom       zumm



    t1 data after record changes
    t1
    a1         a2         a3
    ---------- ---------- ----------
    foo        bar        fizz
    yin        yang       zen
    vini       vidi       vici
    lug        lag        lugger
    dig        dug        digger
    zimm       zoom       zumm
    riki       tiki       tavi
    yuz        wuz        wiz
    bip        bap        boop
    zip        zap        zing
    ding       aling      aling
    yuz        wuz        wiz
    bip        bap        boop
    zip        zap        zing
    ding       aling      aling

*/