I'm doing a fair amount of guessing here, but this is how I imagine that your model should look like. In a couple of tables I removed id columns to make it clearer, you may want to put them back in case the keys I have chosen is not stable enough:
CREATE TABLE `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(100),
`password` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE(`name`) -- questionable
);
insert into users(name, password) values ('bob', 'passwd');
CREATE TABLE `stock` (
stock_code varchar(100) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (stock_code)
);
insert into stock(stock_code) values('AABC'), ('BBCC'), ('EEFF');
-- a user can have 0 or more stocks, a stock have 1 user
create table user_stock (
user_id int(10) unsigned NOT NULL,
stock_code varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`value` double DEFAULT NULL,
PRIMARY KEY (stock_code),
constraint fk1_user_stock foreign key (user_id)
references `users` (id)
on delete cascade
on update cascade,
constraint fk2_user_stock foreign key (stock_code)
references stock (stock_code)
on delete cascade
on update cascade
);
insert into user_stock(stock_code, value, user_id)
values('AABC', 10, 1), ('BBCC', 4.5, 1), ('EEFF', 7, 1);
CREATE TABLE `sector_a` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(100) CHARACTER SET utf8 DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE(name)
);
insert into sector_a(name) values('FOOD'), ('CAR'), ('BUILDING');
-- a stock can belong to 0 or more sectors, a sector can have 0 or more stocks
CREATE TABLE `stock_sector_a` (
stock_code varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`sector_id` int(10) unsigned not NULL,
PRIMARY KEY (stock_code, sector_id),
constraint fk1_stock_sector_a foreign key (stock_code)
references stock (stock_code)
on delete cascade
on update cascade,
constraint fk2_stock_sector_a foreign key (sector_id)
references sector_a (id)
on delete cascade
on update cascade
);
insert into stock_sector_a(stock_code, sector_id)
values('AABC', 1), ('AABC', 2), ('AABC', 3), ('BBCC', 2), ('BBCC', 3);
MariaDB [test]> delete from stock where stock_code = 'AABC';
Query OK, 1 row affected (0.01 sec)
MariaDB [test]> select * from user_stock;
+---------+------------+-------+
| user_id | stock_code | value |
+---------+------------+-------+
| 1 | BBCC | 4.5 |
| 1 | EEFF | 7 |
+---------+------------+-------+
2 rows in set (0.00 sec)
MariaDB [test]> select * from stock_sector_a;
+------------+-----------+
| stock_code | sector_id |
+------------+-----------+
| BBCC | 2 |
| BBCC | 3 |
+------------+-----------+
2 rows in set (0.00 sec)
Best Answer
Max.