2

i have a table like

CREATE TABLE IF NOT EXISTS grouped_executions (
    id             INTEGER UNSIGNET NOT NULL ,
    execution_id   INTEGER UNSIGNED NOT NULL REFERENCES execution.execution_id ,
    president      BOOLEAN NOT NULL DEFAULT 0

    PRIMARY KEY ( id, execution_id )
) ENGINE = InnoDB ;

all i want is to make president unique in a group of rows with same id.

for example: i have such data:

id | execution_id | president
= - = - = - = - = - = - = - =
1  | 1            | 0
1  | 2            | 1
1  | 3            | 0
1  | 4            | 0
i want mysql prevents inserting new row with id = 1 & president = 1

( of course i can make another table that holds president of a group but is above structure possible? )

everplays
  • 143
  • 1
  • 7

3 Answers3

3

Yes, you can add a unique-constraint for the combination of the two columns.

Community
  • 1
  • 1
David Hedlund
  • 128,221
  • 31
  • 203
  • 222
  • but i have many rows with id = 1 & president = 0, if i do "UNIQUE KEY `grouped_executions_id_president` ( `id`, `president` )" i can't have em – everplays Dec 07 '10 at 08:40
  • oh, sorry, I got your question wrong, then. I don't know that you can specify uniqueness only for specific values like that in MySQL (I could be wrong). A workaround might be using a trigger to validate an insert or update. – David Hedlund Dec 07 '10 at 08:50
1

You may want to try to set default NULL for president as unique key allows multiple NULL values, but then, it kind of make no sense to have a bool with only one 1 and many NULLs, but no 0. If you don't want to set other mechanisms like triggers (suggested by @David Hedlund), you better of with another table for that relationship (as you mentionned it). This way, if you one day wants a unique "secretary" or "treasury", it would be easy to define a new table instead of having that trigger (or another one) verify for this relationship.

Danosaure
  • 3,578
  • 4
  • 26
  • 41
-1

Have you tried this?

ALTER TABLE grouped_executions ADD CONSTRAINT PRIMARY KEY (id, president);
Conner
  • 30,144
  • 8
  • 52
  • 73
AnD
  • 3,060
  • 8
  • 35
  • 63
  • mysql> ALTER TABLE grouped_executions ADD CONSTRAINT PRIMARY KEY (id, president); ERROR 1068 (42000): Multiple primary key defined – everplays Dec 07 '10 at 08:55