如何进行此查询

时间:2016-12-26 18:41:29

标签: php mysql database database-design

user
- - - - - - - - - - - - - - -
id        last_activity
500       8:00PM
100       7:00PM
200       2:00PM

institution
- - - - - - - - - - - - - - -
user_id        name
500            Harvard Institution

instructor
- - - - - - - - - - - - - - -
user_id        job_title        fname        lname
100            Dr.              Alex         Adam

student
- - - - - - - - - - - - - - -
user_id        fname        lname        reg_code
200            Smith        Mark         RdT1v4dq

announcement
- - - - - - - - - - - - - - -
id        institution_id        title
900       500                   Announcement Title!

announcement_replay
- - - - - - - - - - - - - - -
announcement_id        user_id        content
900                    200            Hello, I'm student Smith
900                    100            Hello, I'm instructor Alex
900                    500            Hello, I'm Harvard Institution

在此架构中,如何选择发布 announcement_replay 用户名称

例如我想得到的东西:

query result
- - - - - - - - - - - - - - -
announcement_id        institution        instructor        student        content
900                    null               null              Smith Mark     Hello, I'm student Smith
900                    null               Dr. Alex Adam     null           Hello, I'm instructor Alex
900                    Harvard            null              null           Hello, I'm Harvard Institution

所以我可以通过 php 在页面中列出它们,并使用null来确定用户类型是什么。

此架构也更好吗?

institution: id, name;
    instructor: institution.id, job_title, fname, lname;
    student: institution.id, fname, lname, reg_code;
        ann: id, institution.id, title;
            ann_replay: id, ann.id, content;
                ann_replay_instructor: ann_replay.id, instructor.id;
                ann_replay_student: ann_replay.id, student.id;

1 个答案:

答案 0 :(得分:5)

SELECT
  ar.announcement_id,
  ins.name institution,
  concat(i.job_title,' ', i.fname, ' ', i.lname) instructor,
  concat(s.fname, ' ', s.lname) student,
  ar.content
FROM
  announcement_replay ar
LEFT OUTER JOIN student s
ON
  ar.user_id = s.user_id
LEFT OUTER JOIN instructor i
ON
  ar.user_id = i.user_id
LEFT OUTER JOIN institution ins
ON
  ar.user_id = ins.user_id;

我认为这很好(做了一些改动):

institution: id, name;
instructor: instructor_id, job_title, fname, lname, institution.id;
student: student_id, fname, lname, reg_code, institution.id;
ann: id, institution.id, title;
ann_replay: id, ann.id, content;
ann_replay_instructor: ann_replay.id, instructor.id;
ann_replay_student: ann_replay.id, student.id;