带条件的Mysql查询更新

时间:2016-04-21 12:49:45

标签: mysql join conditional

我有一个带数据加载的现有Mysql表(TblParts)

Code Stock Price Location id
1     10   1000   Global  1
2     5    1500   Office  2
3     2    500    Global  3
4     1    100    Global  4

我有一个包含新信息的第二张表(TblNewParts)

Code Stock Price Location id
1    30    2000    Global 1
2    5     1000    Global 2
3    10    5000    Global 3
4    30    200     Global 4
5    40    500     Global 5

我需要使用TblPartsNew数据更新TblParts

如果代码存在,并且位置=全局,则在代码存在时更新股票和价格,但位置<>全局然后插入具有相同代码和不同位置的记录,如果代码不存在则添加

TblParts的输出必须是:

Code Stock Price Location
1    30    2000   Global 
2    5     1500   Office 
3    10    5000   Global 
4    30    200    Global 
5    40    500    Global

2 个答案:

答案 0 :(得分:0)

第1步:使用以下查询为列(代码,位置)创建主键

insert into TblParts(Code,Stock,Price,Location) select (Code,Stock,Price,Location) from TblNewParts on duplicate key update Stock=values(Stock),Price=values(Price);

第2步:现在使用以下查询使用 TableNewParts 表格数据更新表格

if today = Monday

答案 1 :(得分:0)

试试这个:

/* if Code Exist, And Location = Global then Update Stock and Price */
UPDATE 
  tblparts p INNER JOIN tblnewparts np 
    ON np.code = p.code AND p.location = 'Global' 
SET p.price = np.price, p.stock = np.stock;

/* if Code Exist, But Location <> Global then Insert Record with Same Code */
/* and Distinct Location */ 
/* if code Not Exist then Add it */
INSERT INTO tblparts (code, stock, price, location)
  SELECT code, stock, price, location 
  FROM tblnewparts np
  WHERE NOT EXISTS ( SELECT * FROM tblparts 
                     WHERE (code = np.code AND location = np.location) 
                           OR 
                        (code= np.code)) 

不知道ID列代表什么。如果它是一个自动增量键,只需将0添加到INSERT语句下的字段列表中:

INSERT INTO tblparts (code, stock, price, location, id)
  SELECT code, stock, price, location, 0 
  FROM tblnewparts np
  WHERE NOT EXISTS ( SELECT * FROM tblparts 
                     WHERE (code = np.code AND location = np.location) 
                           OR 
                        (code= np.code))