This is the data model that I referred to in my comment. I explain it briefly:
Having said that, I leave you an example based on real data. Next, all the code for creating tables and inserting test data:
/*MYSQL: Estudiantes y centros tabla asociativa - https://es.stackoverflow.com/q/185957/29967*/
CREATE TABLE IF NOT EXISTS student
(
student_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
carnet VARCHAR(12),
student_name VARCHAR(50),
CONSTRAINT student_AK01 UNIQUE (carnet)
)ENGINE=INNODB;
CREATE TABLE IF NOT EXISTS headquarter
(
hq_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
headquarter VARCHAR(150),
CONSTRAINT headquarter_AK01 UNIQUE (headquarter)
)ENGINE=INNODB;
CREATE TABLE IF NOT EXISTS student_headquarter
(
carnet VARCHAR(12),
hq_id INT,
type TINYINT,
CONSTRAINT student_headquarter_PK PRIMARY KEY (carnet,hq_id,type),
FOREIGN KEY (carnet) REFERENCES student(carnet)
ON UPDATE CASCADE ON DELETE CASCADE,
FOREIGN KEY (hq_id) REFERENCES headquarter(hq_id)
ON UPDATE CASCADE ON DELETE CASCADE
)ENGINE=INNODB;
INSERT INTO student (student_name, carnet)
VALUES
('Pedro', 'P-01'),
('Santiago', 'S-01'),
('Juan', 'J-01') ;
INSERT INTO headquarter (headquarter)
VALUES
('Sede 1'),
('Sede 2'),
('Sede 3'),
('Sede 4'),
('Sede 5');
INSERT INTO student_headquarter (carnet,hq_id,type)
VALUES
('P-01',1,1),
('P-01',5,2),
('S-01',2,1),
('S-01',3,2),
('J-01',4,1),
('J-01',1,2),
('P-01',2,2);
Let's now try a query like this:
SELECT
s.carnet,
s.student_name,
h.headquarter,
sh.type
FROM student_headquarter sh
INNER JOIN student s ON sh.carnet=s.carnet
INNER JOIN headquarter h ON sh.hq_id=h.hq_id;
Result:
carnet student_name headquarter type
---------------------------------------------------
P-01 Pedro Sede 1 1
P-01 Pedro Sede 2 2
P-01 Pedro Sede 5 2
S-01 Santiago Sede 2 1
S-01 Santiago Sede 3 2
J-01 Juan Sede 1 2
J-01 Juan Sede 4 1
What does the result show? If we take the case of Pedro
, we see that the student is enrolled in Sede 1
in a type 1
(student) and that has done training ( type 2
) in Sede 2
and in Sede 5
.
I must also say that this model will allow you to do very easily things that otherwise would be very complicated, such as grouping data by any of the columns involved, making calculations, etc.
Demonstration
Here you can see a COMPLETE DEMONSTRATION of the data used in the response .
I hope you find it useful.