我有两个相同数据库的表说D,两个表是T1和T2。 T1具有属性a1,a2 ...... an和t2具有属性a1,a2。我想要一个查询,只有当T1.a1 = T2.a1时才能更新T1的值,并且只能在T1中插入T1。实施例:
答案 0 :(得分:0)
您至少有三个选择:
create as select
以重新创建表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
*/