MySQL连接:使用“where”子句显示表中的所有行

时间:2012-03-05 11:28:51

标签: mysql join

我有以下表格:

slots = id,时间

child = id,parent_id,name,form

parent = id,name,contact_details

teacher = id,name,subject

appointments = id,child_id,slot

我正在使用以下代码显示可预订的预约时间列表:

SELECT s.id, DATE_FORMAT( s.time,  '%l:%i' ) AS TIME, p.name
FROM slots AS s
LEFT JOIN appointments AS a ON a.slot = s.id
LEFT JOIN child AS c ON a.child_id = c.id
LEFT JOIN parent AS p ON c.parent_id = p.id

这会显示我所有约会时段的列表以及一些带有父名称的列表。

我想做的是,针对特定教师显示所有预约空档的列表,如果有些已经填写,我想显示名称已预订该位置的孩子的父母

例如,

布鲁姆菲尔德小姐的任命:

id  TIME    name
1   4:00    Parent One
2   4:05    NULL
3   4:10    Parent Two
4   4:15    NULL
5   4:20    NULL
6   4:25    NULL
7   4:30    NULL

这可能吗?我尝试过使用WHERE子句,但只显示预约的约会,而不是完整的可用时间列表。

我因此意识到我很确定我的JOIN完全错了!


更新:插槽表如下所示:

SQL result

Host: localhost
Generation Time: Mar 05, 2012 at 11:43 AM
Generated by: phpMyAdmin 3.4.9 / MySQL 5.5.20
SQL query: SELECT * FROM `slots` LIMIT 0, 30 ; 
Rows: 30

id  time
1   2012-03-15 16:00:00
2   2012-03-15 16:05:00
3   2012-03-15 16:10:00
4   2012-03-15 16:15:00
5   2012-03-15 16:20:00
6   2012-03-15 16:25:00
7   2012-03-15 16:30:00
8   2012-03-15 16:35:00
9   2012-03-15 16:40:00
10  2012-03-15 16:45:00
11  2012-03-15 16:50:00
12  2012-03-15 16:55:00
13  2012-03-15 17:00:00
14  2012-03-15 17:05:00
15  2012-03-15 17:10:00
16  2012-03-15 17:15:00
17  2012-03-15 17:20:00
18  2012-03-15 17:25:00
19  2012-03-15 17:50:00
20  2012-03-15 17:55:00

提前致谢,

2 个答案:

答案 0 :(得分:1)

来自IRC的朋友的回答似乎已经成功了:

SELECT s.id, DATE_FORMAT( s.time,  '%l:%i' ) AS time, p.name
FROM slots AS s
LEFT JOIN appointments AS a ON a.slot = s.id
AND teacher_id =$teacher
LEFT JOIN child AS c ON a.child_id = c.id
LEFT JOIN parent AS p ON c.parent_id = p.id

AND 行很重要!

答案 1 :(得分:1)

或者您可以将以下内容放在WHERE

WHERE appointments.teacher_id =$teacher OR appointments.teacher_id IS NULL