从5个连接表中查询

时间:2017-10-22 05:24:57

标签: mysql sql

所以我有5个表如下:

CREATE TABLE student (
  id   serial PRIMARY KEY,
  name varchar(255) NOT NULL
  -- other columns, constraints, etc...
);
CREATE TABLE teacher (
  id   serial PRIMARY KEY,
  name varchar(255) NOT NULL
  -- other columns, constraints, etc...
);
CREATE TABLE course(
  id   serial PRIMARY KEY,
  name varchar(255) NOT NULL
  -- other columns, constraints, etc...
);
CREATE TABLE student_course (
  student_id integer NOT NULL REFERENCES student(id),
  course_id  integer NOT NULL REFERENCES course(id)
);
CREATE TABLE teacher_course (
  teacher_id integer NOT NULL REFERENCES teacher(id),
  course_id  integer NOT NULL REFERENCES course(id)
);

我想询问哪个学生在哪个老师的哪个课程学习。

SELECT s.name, c.name, t.name
FROM student s
  JOIN student_course sc ON s.id = sc.student_id
  JOIN course c ON sc.course_id = c.id
  JOIN teacher_course tc ON c.id = tc.course.id
  JOIN teacher t ON tc.teacher_id = t.id

但结果不是我想要的。比如1名学生用2名不同的老师学习一门科目。这不是输入问题,因为我检查并且在teacher_course和student_course中没有重复的输入。所以我认为问题出在我的查询上。有人能告诉我哪里出错了吗?

Here's the output

2 个答案:

答案 0 :(得分:1)

你的sql语句似乎是正确的。我使用了LEFT JOIN,因为JOIN默认是INNER JOIN(参见What is the default MySQL JOIN behaviour, INNER or OUTER?)。但是,根据您的表格语法,我使用JOIN和LEFT JOIN应用了sql语句,并且我收到了相同的结果。无论如何,我的LEFT JOIN的sql语句是:

SELECT 
    s.*,
    c.*,
    t.*
FROM student AS s
LEFT JOIN student_course AS sc ON sc.student_id = s.id
LEFT JOIN course AS c ON c.id = sc.course_id
LEFT JOIN teacher_course AS tc ON tc.course_id = c.id
LEFT JOIN teacher AS t ON t.id = tc.teacher_id;

如果问题与你说的那样 - " 就像1名学生一样,有2名不同的老师学习" - 然后原因只能是您将多个teacher_id分配给表course_id中的同一teacher_courses

请注意,一位教师可以教多门课程的情况是有效的。例如。允许在teacher_course中为多个teacher_id提供相同的course_id

答案 1 :(得分:1)

试试这个

function type(obj) {
  return Object.prototype.toString.call(obj).split(' ')[1].replace(']', '');
}

function is(obj, what) {
  let regex = new RegExp('\\b(' + type(obj) + ')\\b', 'i');
  if (regex.test(what)) {return true;}
  return false;
}

unknown1 = 'hello world'
unknown2 = /a/g
unknown3 = null
unknown4 = undefined
unknown5 = 9
unknown6 = function name() {}
unknown7 = true
unknown8 = {}


console.log(is(unknown1, 'a string or function'))
console.log(is(unknown2, 'a regexp'))
console.log(is(unknown3, 'null, regexp, or string'))
console.log(is(unknown4, 'string'))
console.log(is(unknown5, 'string'))
console.log(is(unknown6, 'regexp'))
console.log(is(unknown7, 'a boolean'))
console.log(is(unknown8, 'an object'))

结果:

enter image description here