Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

mysql - Update multiple rows with known keys without inserting new rows if nonexistent keys are found

Let's imagine that we have table items...

table: items
item_id INT PRIMARY AUTO_INCREMENT
title VARCHAR(255)
views INT

Let's imagine that it is filled with something like

(1, item-1, 10),
(2, item-2, 10),
(3, item-3, 15)

I want to make multi update view for this items from data taken from this array [item_id] => [views]

'1' => '50',
'2' => '60',
'3' => '70',
'5' => '10'

IMPORTANT! Please note that we have item_id=5 in array, but we don't have item_id=5 in database.

I can use INSERT ... ON DUPLICATE KEY UPDATE, but this way image_id=5 will be inserted into talbe items. How to avoid inserting new key? I just want item_id=5 be skipped because it is not in table.

Of course, before execution I can select existing keys from items table; then compare with keys in array; delete nonexistent keys and perform INSERT ... ON DUPLICATE KEY UPDATE. But maybe there is some more elegant solutions?

Thank you.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You may try to generate a table of literals and update items by joining with the table:

UPDATE items
    JOIN (SELECT 1 as item_id, 50 as views
          UNION ALL
          SELECT 2 as item_id, 60 as views
          UNION ALL
          SELECT 3 as item_id, 70 as views
          UNION ALL
          SELECT 5 as item_id, 10 as views
          ) as updates
         USING(item_id)
 SET items.views = updates.views;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...