更新表,如果存在,则插入

时间:2016-12-18 04:38:22

标签: mysql sql

我有一个名为

的表
userindex bts   userid          accountnumber   isalepo
119459  190900  a@qubee.com.bd  000000000000004 0
31513   1a1430  b@qubee.com.bd  000000000000008 0
36981   196100  c@qubee.com.bd  000000000000018 0
56215   197200  d@qubee.com.bd  000000000000062 1
145938  199000  e@qubee.com.bd  000000000000066 0
57410   1a1520  f@qubee.com.bd  000000000000067 1
38554   198510  g@qubee.com.bd  000000000000068 0
15595   1a2d10  h@qubee.com.bd  000000000000069 0
30945   1a1120  i@qubee.com.bd  000000000000074 0
156180  190320  j@qubee.com.bd  000000000000081 0

我想只更新bts字段(如果它存在于表b

中)
userindex   bts usage_in_mb
100024  081620  4761.23809814
100044  001320  499.27043915
36981   19f710  1114.07279968
100061  19fb10  10931.33640284
57410   07dc10  108.45470429
100088  164610  1474.35951231
10009   19b700  2920.20797732
100105  19c200  7607.14340212
100110  000610  5771.08287813
156180  194820  1409.85393525

如果表a中不存在userindex,那么我想从b和c表中插入(userindex,bts,userid,accountnumber,isalepo)。表c包含

userindex   accountnumber   userid
100024  000000000094190 aa@qubee.com.bd
100044  000000000000018 bb@qubee.com.bd
36981   000000000000067 cc@qubee.com.bd
100061  000000000214989 dd@qubee.com.bd
57410   000000000187084 ee@qubee.com.bd
100088  000000000236716 ff@qubee.com.bd
10009   000000000211229 gg@qubee.com.bd
100105  000000000236222 hh@qubee.com.bd
100110  000000000237036 ii@qubee.com.bd
156180  000000000000081 jj@qubee.com.bd

我正在尝试此查询

INSERT INTO a
  (
   userindex
  ,bts
  ,userid
  ,accountnumber
  ,isalepo
  ,crestelbts
)
SELECT b.userindex
,b.bts
,c.USERID
,c.accountnumber
,1
,0
FROM b  
left join  c on b.userindex=c.userindex
ON DUPLICATE KEY UPDATE
bts = VALUES(b.bts);

2 个答案:

答案 0 :(得分:1)

来自docs

  

如果指定ON DUPLICATE KEY UPDATE,则插入一行   会导致 UNIQUE 索引或 PRIMARY KEY 中的重复值,MySQL   执行旧行的更新。例如,如果列a是   声明为UNIQUE并包含值1,以下两个   陈述有类似的效果:

此行为是因为您没有唯一键或主键。所以你需要

ALTER TABLE a ALter table fts add primary key(userindex) 

ALTER TABLE a ALter table fts add unique key(userindex) 

答案 1 :(得分:0)

来自MySQL的Documentation, 你可以试试这个:

INSERT INTO a (userindex,bts,userid,accountnumber,isalepo,crestelbts) 
 SELECT b.userindex ,b.bts ,c.USERID ,c.accountnumber ,1 ,0
FROM b left join  c on b.userindex=c.userindex
WHERE NOT EXISTS ((SELECT * FROM b WHERE b.userindex = a.userindex) OR (
   SELECT * FROM c WHERE c.userindex = a.userindex ));