Reputation: 347
This is my DB schema:
CREATE TABLE `members` (
`m_id` int NOT NULL AUTO_INCREMENT,
`m_name` varchar(355),
`m_email` varchar(20) UNIQUE,
PRIMARY KEY (`m_id`)
);
CREATE TABLE `schools` (
`s_id` int NOT NULL AUTO_INCREMENT,
`s_name` varchar(355)
);
CREATE TABLE `schools_members` (
`sm_id` int NOT NULL AUTO_INCREMENT,
`sm_school_id` int NOT NULL,
`sm_member_id` int NOT NULL,
FOREIGN KEY (sm_school_id) REFERENCES schools(s_id),
FOREIGN KEY (sm_member_id) REFERENCES members(m_id)
);
I need to display all members for a selected school by a given school id ($schoolId
). So i assume that the query will touch on schools_members
and members
.
I believe the logic is: select all the sm_member_id
where sm_school_id
= $schoolId
from table schools_members
and then SELECT m_name
and
m_email
for each m_id
(member id) from table members
that is IN the last query result.
This is not required, but now im curious if i want to join to this result the s_name
(school name) from table schools
so that each member displays the name of school also?
Upvotes: 0
Views: 45
Reputation: 133400
You could just use a join between schools_members and members
select m.m_name, m.m_email
from schools_members sm
inner join members m ON m.m_id = sm.sm_member_id
where sm.sm_school_id = Your_value
and for school name
select m.m_name, m.m_email, s.s_name
from schools_members sm
inner join members m ON m.m_id = sm.sm_member_id
inner join schools s on s.s_id = sm.sm_school_id
where sm.sm_school_id = Your_value
Upvotes: 1