在mysql数据库中我存储了5个表。我使用PHP来存储和检索数据。我想以链接的方式检索/回显/显示这5个表的信息。我在每个表上都有academy_id
作为外键。每个学院都有一个联系人。有些学院可能会共用同一个联系人。但不确定如何以独特的信息展示每个学院。如何通过php / mysql select查询显示这些值?
Academy Name | MOU_ID | Academy_ID | STATUS | Academy Created | Course Name | Course Start Date | Instructor First Name | Contact First Name
表
CREATE TABLE IF NOT EXISTS `academies` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(25) NOT NULL,
`mou_id` int(11) default NULL,
`academy_id` int(11) NOT NULL,
`status` enum('INACTIVE','ACTIVE') NOT NULL default 'ACTIVE',
`created_date` date NOT NULL
PRIMARY KEY (`id`)
);
INSERT INTO `courses` (`course_id`, `course_name`) VALUES
(1, 'MATH'),
(2, 'ENGLISH'),
(3, 'BIOLOGY'),
CREATE TABLE IF NOT EXISTS `academy_courses` (
`unique_id` int(11) NOT NULL auto_increment,
`academy_id` int(11) NOT NULL,
`course_id` int(11) NOT NULL,
`start_date` date default NULL,
PRIMARY KEY (`unique_id`),
KEY `course_id` (`academy_id`,`course_id`)
);
CREATE TABLE IF NOT EXISTS `instructors` (
`instructor_id` int(11) NOT NULL auto_increment,
`academy_id` int(11) NOT NULL,
`instructor_fname` varchar(50) NOT NULL
PRIMARY KEY (`instructor_id`),
KEY `academy_id` (`academy_id`)
);
CREATE TABLE IF NOT EXISTS `main_contact` (
`contact_id` int(11) NOT NULL auto_increment,
`academy_id` int(11) NOT NULL,
`contact_fname` varchar(50) NOT NULL,
PRIMARY KEY (`contact_id`),
KEY `academy_id` (`academy_id`)
);
CREATE TABLE IF NOT EXISTS `main_contact_bridge` (
`academy_id` int(11) NOT NULL,
`contact_id` int(11) NOT NULL,
PRIMARY KEY (`contact_id`,`academy_id`),
KEY `academy_id` (`academy_id`)
);
答案 0 :(得分:1)
我认为这是你想要得到的:
SELECT a.name, a.mou_id, a.academy_id, a.status, a.created_date, ac.course_id, ac.start_date, i.instructor_fname, mc.contact_fname
FROM academy_courses ac
LEFT JOIN academies a USING (academy_id)
LEFT JOIN instructors i USING (academy_id)
LEFT JOIN main_contact mc USING (academy_id);
答案 1 :(得分:1)
我会将instructor_id添加到academy_courses中,否则如果您有多个教师,您将获得每个教师的所有重复数据。然后你会这样做:
SELECT a.name AS 'Academy Name',
a.mou_id AS
a.academy_id
a.status
a.created_date AS 'Academy Created',
c.course_name AS 'Course Name',
ac.start_date AS 'Course Start Date',
i.instructor_fname AS 'Instructor First Name',
co.contact_fname AS 'Contact First Name'
FROM academies a
INNER JOIN academy_courses ac ON a.id = ac.academy_id
INNER JOIN courses c ON c.id = ac.course_id
INNER JOIN instructors i ON i.instructor_id = ac.instructor_id
INNER JOIN main_contact co ON co.academy_id = a.id
如果您想从Academy获取信息,即使课程/ academy_courses / etc不存在,您也可以写一个LEFT JOIN。
答案 2 :(得分:0)
您正在寻找的是加入表格。有不同类型的连接。请查看此解释http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html