用左连接查询选择mysql

时间:2014-08-06 01:08:41

标签: mysql

我的代码是

select class.name as classname,
       class.hours as hours, 
       teachers.first_name as teacherFirstName, 
       teachers.last_name as teacherLastName 
from teachers,class 
left join class_teachers cl on class.id = cl.class_ref  
left join class_teachers cl1 on teachers.id = cl1.teachers_ref

出现错误

#1054 - Unknown column 'teachers.id' in 'on clause

当我与班级和老师交换时,错误是

#1054 - Unknown column 'class.id' in 'on clause
你知道这个问题吗?

修改

CREATE TABLE `class` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `hours` int(3) NOT NULL,
  PRIMARY KEY (`id`)
)

CREATE TABLE `class_teachers` (
  `class_ref` int(11) NOT NULL,
  `teachers_ref` int(11) NOT NULL
)

CREATE TABLE `teachers` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(100) NOT NULL,
  `last_name` varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
)

class_teachers是一个中间表。这个数据库应该使一个班级应该有多个老师。例如,体育课可以为男孩和女孩分别设立教师。查询应显示具有教师姓名,班级名称和课时数

的班级列表

班级表

id  name     hours
1   science     3
2   math        5

教师表

id  first_name  last_name
1   Ronald      Manlapao
2   hello       goodbye
3   elise       elise
4   me          me

class_teachers表

class_ref   teachers_ref
2                   2
1                   1

1                   2

尝试

select c.name as classname, c.hours as hours, t.first_name as teacherFirstName, t.last_name as teacherLastName 
from teachers t, class c
left join class_teachers cl on (c.id = cl.class_ref and t.id = cl.teachers_ref)

但仍然是同样的错误

将class_teachers表更新为class_teachers_section以包含section。这个想法是一个班级可以包括不同教师的不同部分。例如,1年级的PE课程可以包括所有部分(让我们假装3个部分)...男孩的老师会因女孩而异;

select class.name as classname, 
   class.hours as hours, 
   teachers.first_name as teacherFirstName, 
   teachers.last_name as teacherLastName,
   section.name as sectionName
 from class_teachers_section cls 
 left join class on class.id = cls.class_ref  
 left join teachers on teachers.id = cls.teachers_ref
 left join section on section.id = cls.section_ref
 where section.name = 'grade 1'

1 个答案:

答案 0 :(得分:0)

我建议您将主表更改为class_teachers,并且应引用教师和类表。

select class.name as classname, 
       class.hours as hours, 
       teachers.first_name as teacherFirstName, 
       teachers.last_name as teacherLastName 
from class_teachers cl 
left join class on class.id = cl.class_ref  
left join teachers on teachers.id = cl.teachers_ref

你的问题是你在from a,b之前使用left join,那么left join on子句只能找到b.id,所以当你和班级老师交换时,你会得到不同的错误

如果您真的想首先交叉加入老师和班级,请使用join ,的{​​{1}}。 使用left joinfull outer join将是相同的,因为您已经有任何加入条件。

select class.name as classname,
       class.hours as hours, 
       teachers.first_name as teacherFirstName, 
       teachers.last_name as teacherLastName 
from teachers
join class 
left join class_teachers cl 
     on  class.id = cl.class_ref  
     and teachers.id = cl.teachers_ref