I have the following table structure:
OFFER_ID -|- COUNTRY -|- URL
1 -|- GB -|- http://www.example.com/1
1 -|- US -|- http://www.example.com/2
1 -|- FR -|- http://www.example.com/3
What I want is to update the URL when BOTH the OFFER_ID and GB are already existent within the table.
For example, if the query was:
INSERT INTO table_name (offer_id, country, url) VALUES ('1','DE', 'http://www.example.com/3')
OR
INSERT INTO table_name (offer_id, country, url) VALUES ('2','FR', 'http://www.example.com/4')
A new row would be inserted as although the values for OFFER_ID (in ex. 2) and COUNTRY (in ex. 1) are new, the values for COUNTRY (in ex. 2) and OFFER_ID (in ex. 1) aren't.
However, with a query like this:
INSERT INTO tabl开发者_如何学Goe_name (offer_id, country, url) VALUES ('1','FR', 'http://www.example.com/7')
The URL column would be updated.
I know using ON DUPLICATE KEY UPDATE url=VALUES(url) would be the way forward, but how would I be able to structure it so that ONLY when both OFFER_ID and COUNTRY are not unique, the URL column is updated as oppose to a new row being inserted?
Any help would be greatly appreciated :)!
Create a unique index on (OFFER_ID, COUNTRY), and ON DUPLICATE KEY UPDATE will work:
ALTER TABLE foo
ADD UNIQUE INDEX offer_id_country (OFFER_ID, COUNTRY);
Or a primary key if you don't have one already:
ALTER TABLE foo
ADD PRIMARY KEY (OFFER_ID, COUNTRY);
You can make both a part of the primary key
PRIMARY KEY (`offer_id`, `country`)
You just need to set the primary key for that table to (OFFER_ID,COUNTRY). (Or set a UNIQUE constraints on that pair of columns.)
Try using Mysql's REPLACE function. After creating a unique key on (OFFER_ID, COUNTRY).
REPLACE INTO table_name (offer_id, country, url) VALUES ('1','FR', 'http://www.example.com/7')
加载中,请稍侯......
精彩评论