In MySQL db, I have a table with users' addresses:
CREATE TABLE `user_address` (
`id` INT(10) NOT NULL AUTO_INCREMENT,
`user_id` INT(10) NOT NULL,
`street` VARCHAR(50) NULL DEFAULT NULL,
`number` VARCHAR(255) NULL DEFAULT NULL,
`city` VARCHAR(255) NULL DEFAULT NULL,
`zip` VARCHAR(255) NULL DEFAULT NULL,
`is_main` TINYINT(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
)
The number of addresses per user is not limited, but I want the is_main to be 1 only once per user, to indicate the main user's address. All other user's addresses will have is_main = 0.
Can this be restricted anyhow on the MySQL level?
(ALTER TABLE user_address
ADD UNIQUE INDEX is_main (is_main, user_id); didn't help as there are several records with is_main=0...)
is_main, user_id, but you can only have 2 addresses then (one with is_main = 1 and one with is_main = 0). You need to restrict it another way then, in your code for example. Before you insert it, do a check if there are any rows with is_main = 1.