简体   繁体   中英

Combined primary keys in MySQL

This may sound a bit daft - but I would like to set up the following scenario:

ClientID,AdvertID  
  1,1  
  2,1  
  3,1  
  2,2  
  2,3  
  1,2  

Thus, both ClientID and AdvertID must be primary keys, but only AdvertID is auto-incremental. AdvertID must restart numbering relevant to which ClientID it's being linked to. Also, ClientID will be a foreign key as well.

What I have done thus far was just create a combined primary key when I created the table in PHPMyAdmin, but this just continues the auto-incremental value without regard to the actual clientID

Does anybody know how to do this? I know it is possible, I have seen it before. I just have no idea how it was done.

Thanks in advance!

PS: Just to be clear, this is for MySQL v5.5

LOCK TABLES tbl WRITE;

select AdvertID from tbl where ClientID = :c_id //save the number somewhere

insert into tbl (ClientID, AdvertID) value (:c_id, :saved_ad_id+1)

UNLOCK TABLES

First, gain exclusive write access to the table (just to be sure to avoid race conditions)

then, search the current advert value of your client, if necessary convert the null to a 0, then increase it +1

Third step, save the couple in the database

At last, unlock the table(s).

There is no need of auto incrementing fields, because there are no REAL auto incrementing fields in this table.

As far as I know, you cannot design a structure which will take care of when the value should restart its incrementing depending on its parent key. It depends on your Server-Side logic (in your case PHP) to make relevant cases whenever a new ClientID is recieved, to start populating AdvertID from the beginning.

我能想象的唯一一件事是插入前触发器,该触发器为您的键执行自动计数逻辑。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM