多个GROUP BY根据WHERE条件查找多行

时间:2013-06-18 04:24:57

标签: mysql sql group-by

我有一张关于机构时间表分配的表格。我必须弄清楚在一个时期内同一房间是否有多个分配,这意味着在特定时期内不应有任何分配多个房间。

此问题的相关字段的表结构如下:

teacherid  subjectid groupname room  day  period 

  1           213        2       1    4      3
  2           123        4       1    5      3

依旧......

如何在一个时间段内返回具有多个分配的房间。

2 个答案:

答案 0 :(得分:1)

select distinct room from table t1 where exists
(select count(*) c1 from table where t1.room = room 
and t1.day=day and t1.period = period having c1>1);

如果不需要考虑日期:

select distinct room from table t1 where exists
(select count(*) c1 from table where t1.room = room 
and t1.period = period having c1>1);

答案 1 :(得分:0)

select t1.room
from timetable t1
join timetable t2
    on t1.day = t2.day
    and t1.period = t2.period
    and t1.id > t2.id

连接非常简单 - 它会找到具有理智日期/周期的行,但是有一个值得注意的技巧...在连接条件中的最后一个比较:

and t1.id > t2.id

这有两件事:

  1. 停止加入自己的行
  2. 停止两次碰撞行。如果没有大于(或小于同样好的工作),即如果它是!=,则碰撞行将为连接的每一侧连接一次
  3. 您只询问了房间,但如果您select *,您将获得有关碰撞的所有信息。

相关问题