如何合并两个表中的两个选择?

时间:2019-01-14 19:26:33

标签: php mysql

这是我的数据库架构:

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)
);

我需要按给定的学校ID($schoolId)显示所选学校的所有成员。因此,我假设查询将触及schools_membersmembers

我认为逻辑是:从表sm_member_id中选择所有sm_school_id = $schoolId,然后选择schools_members和 表m_name中每个m_email(成员ID)的m_id(位于最后一个查询结果中)。

这不是必需的,但是现在我很好奇我是否想加入表members中的s_name(学校名称),以便每个成员显示还叫学校名吗?

1 个答案:

答案 0 :(得分:1)

您可以只在学校成员和成员之间使用联接

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 

以及学校名称

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