SQL WHERE与乘法JOIN和GROUP BY

时间:2015-02-14 21:41:51

标签: mysql sql join count group-by

我正在努力让课堂上有重叠的课程安排,我的课程:课程:

COURSE_ID    NAME
11           matematika
22           logika

时间表:

ID COURSE_ID ID_ROOM DAY HOUR
1   11  105 Mon 10am
2   11  105 Wen 10am

class_room:

ID_ROOM LOCATION CAPACITY
105 A   20
205 B   10

我的sql是:

select class_room.ID_ROOM as crid, class_room.LOCATION, schedule.DAY as d, schedule.HOUR as h,  count(courses.COURSE_ID) as count 
  from schedule
  natural join class_room
  natural join courses
  group by crid, d, h
  order by count desc;

我得到了:

crid LOCATION d h count
105 A   Mon 10am    3
105 A   Thu 10am    2
305 C   Mon 11am    1
105 A   Wen 10am    1
205 B   Wen 10am    1

但我只需要显示计数超过1的行。 我试过

select class_room.ID_ROOM as crid, class_room.LOCATION, schedule.DAY as d, schedule.HOUR as h,  count(courses.COURSE_ID) as count 
  from schedule
  natural join class_room
  natural join courses
  where count>1
  group by crid, d, h
  order by count desc;

但我得到1054错误 怎么解决这个问题?

2 个答案:

答案 0 :(得分:0)

请勿使用where。使用having

select class_room.ID_ROOM as crid, class_room.LOCATION, schedule.DAY as d, schedule.HOUR as h,  count(courses.COURSE_ID) as count 
  from schedule
  natural join class_room
  natural join courses
  group by crid, d, h
  having count>1
  order by count desc;

答案 1 :(得分:0)

删除count > 1,然后添加having count(courses.COURSE_ID) > 1

删除群组