duanjiongzhen2523 2011-09-18 12:00 采纳率: 0%
浏览 82
已采纳

使两列具有唯一键,但仅在两者匹配时?

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 table_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 :)!

  • 写回答

4条回答 默认 最新

  • doucao8982 2011-09-18 12:08
    关注

    You can make both a part of the primary key

    PRIMARY KEY (`offer_id`, `country`)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?