I’m new here. I thought I could ask for some help here on my php-sql homework.
I’ve been trying to extract all the sports associated to a registered person using SQL.
There are three tables in my mySql.
personnes which stores the individuals
[id] [sexe] [etat_civil] [nom] [prenom]
1 Homme M. Smith Alex
2 Femme Mme Alisha Elektra
3 Femme Mll Lord Yves
loisirs which stores the types of sports or leisures
id nom
1 Sport
2 Concert
3 Jeux vidéo
4 Jeux société
5 Voyage
6 Cinéma
7 Lecture
8 Théâtre
9 Danse
10 Animaux
11 Randonnée
12 Shopping
personnes_loisirs which stores the foreign key of the individuals which associated foreign keys id.
[id] [fk_personnes] [fk_loisirs]
1 1 1
2 1 2
3 1 3
4 2 1
5 2 3
6 2 4
7 2 5
8 3 7
9 3 8
10 3 9
Basically, I’ve been successful to extract the sport of a user but only if there’s only 1 sport associated to him. Where there are more than 1, I fail to get the rest of it.
Here’s the SQL
select nom
from `loisirs`
where id in
(select fk_loisirs
from `personnes_loisirs`
where id in
(select id
from `personnes`
where sexe='Homme' AND nom='Smith' AND prenom='Alex'))
This returns me ‘Sport’ but not ‘Sport, Concert and Jeux Vidéo’;
I think I must use JOIN to be able to retrieve all the ‘loisirs’ associated to SmithAlex
But I’m not sure how.
Please help.
1 Answer