使用NOT EXISTS的空表

时间:2013-03-13 17:25:04

标签: mysql

我有一个问题:

SELECT g.name, s.hour, gs.weekday
FROM schedule s
INNER JOIN group_schedule gs ON gs.schedule_id = s.id
INNER JOIN groups g ON g.id = gs.group_id
WHERE EXISTS (
  SELECT *
  FROM group_schedule
  WHERE group_id =6
)
ORDER BY g.name, gs.weekday

返回:

name    hour        weekday
A1-A2   10:00:00    1
A1-A2   17:00:00    1
A1-A2   10:30:00    1
A1-A2   17:30:00    1
A1-A2   18:00:00    2
A1-A2   11:30:00    2
A1-A2   18:30:00    2
A1-A2   11:00:00    2
A1-A2   12:30:00    3

但我也需要获得没有这些组合的行,例如:

name   hour      weekday
A1-A2  10:30:00  1
A1-A2  11:00:00  1
A1-A2  11:30:00  1
...

如果我使用NOT EXISTS,我会获得一张空表。

1 个答案:

答案 0 :(得分:0)

我不知道,但你的意思是:

SELECT g.name, s.hour, gs.weekday
FROM schedule s
INNER JOIN group_schedule gs 
ON gs.schedule_id = s.id AND group_id = 6 
INNER JOIN groups g ON g.id = gs.group_id
ORDER BY g.name, gs.weekday

将group_id条件移出一般WHERE子句并移入group_schedule JOIN?您知道在ON关键字后面可以有任意逻辑表达式。