質問

What I am trying to achieve is similar to this example

Singular Upon Key Insert

However where mine differs is im trying to do multiple inserts at the same time. Im updating alot of rows.

I would like the insert to increment the number of sessions figure if its a duplicate

The following (stripped down version) results in a syntax error however it should explain what im trying to achieve

INSERT INTO
`pc_tech`.session_route_data (session_volume,country_origin, pu_date)

VALUES

('1','Switzerland','2012-01-01')
ON DUPLICATE KEY UPDATE  `session_volume` = `session_volume`+1,

('8','Ireland','2012-01-01') 
ON DUPLICATE KEY UPDATE `session_volume` = `session_volume`+8,  

('3','UK','2012-01-01')
ON DUPLICATE KEY UPDATE `session_volume` = `session_volume`+3

Modified changed the inserted value to match the duplicate value as per notes below

役に立ちましたか?

解決

You'll need to do a statement per upsert. It doesn't make sense to the RDBMS to schedule successive upserts like it does for it to schedule successive inserts. In the example of successive inserts, the RDBMS can improve performance by performing one mass insert (with one space allocation, and one write to disk, rather then one per statement.) In the example of upserts, those gains are not guaranteed, In fact if all of the statements end up being updates not inserts, you would lose time, not gain it (you waste time allocating space you don't need and you cant know which blocks to pull ahead of time like you can with an insert.) Therefore most RDBMS's do not provide single statement syntax for this kind of action.

Your syntax will unfortunatly likely need to look like this.

INSERT INTO
`pc_tech`.session_route_data (session_volume,country_origin, pu_date)
VALUES ('1','Switzerland','2012-01-01')
ON DUPLICATE KEY UPDATE  `session_volume` = `session_volume`+1;

INSERT INTO
`pc_tech`.session_route_data (session_volume,country_origin, pu_date)
('8','Ireland','2012-01-01') 
ON DUPLICATE KEY UPDATE `session_volume` = `session_volume`+8; 

INSERT INTO
`pc_tech`.session_route_data (session_volume,country_origin, pu_date)
('3','UK','2012-01-01')
ON DUPLICATE KEY UPDATE `session_volume` = `session_volume`+3;

If you are concerned about concurrency (If you want the scheduler to treat multiple statements like a single statement from a timing and logging standpoint, you'll need to use transactions.)

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top