Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

mysql - 插入MySQL表或更新(如果存在)(Insert into a MySQL table or update if exists)

I want to add a row to a database table, but if a row exists with the same unique key I want to update the row.

(我想向数据库表中添加一行,但是如果存在具有相同唯一键的行,我想更新该行。)

For example,

(例如,)

insert into table (id, name, age) values(1, "A", 19)

Let's say the unique key is id , and in my database there is a row with id = 1 .

(假设唯一键是id ,并且在我的数据库中有一行id = 1 。)

In that case I want to update that row with these values.

(在这种情况下,我想用这些值更新该行。)

Normally this gives an error.

(通常,这会产生错误。)

If I use insert IGNORE it will ignore the error, but it still won't update.

(如果我使用insert IGNORE ,它将忽略该错误,但仍不会更新。)

  ask by Keshan translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use INSERT ... ON DUPLICATE KEY UPDATE

(使用INSERT ... ON DUPLICATE KEY UPDATE)

QUERY:

(查询:)

INSERT INTO table (id, name, age) VALUES(1, "A", 19) ON DUPLICATE KEY UPDATE    
name="A", age=19

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...