【问题标题】:How to make this query happen [closed]如何进行此查询[关闭]
【发布时间】:2016-12-26 18:41:29
【问题描述】:
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;

【问题讨论】:

  • 不要以任何理由破坏您的帖子。

标签: php mysql database database-design


【解决方案1】:
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;

【讨论】:

  • 打败我!这个答案应该正是你要找的
  • 第一个模式和第二个模式哪个更好(速度)?
  • @IbrahimMuhammad 更新
  • 所以这比创建一个“用户”表作为主表要快吗?如果是这样,你能告诉我选择谁来存档相同的结果吗?
猜你喜欢
  • 2012-03-23
  • 2012-01-19
  • 1970-01-01
  • 1970-01-01
  • 2022-01-25
  • 1970-01-01
  • 2015-07-02
  • 1970-01-01
  • 2013-02-17
相关资源
最近更新 更多