根据多个表中的条目排除SQL查询的结果

时间:2011-08-09 17:20:40

标签: mysql sql

我的数据库中有两个表,看起来像这样

CREATE TABLE IF NOT EXISTS `lab_closure_states`
(
state_id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
lab_id INT UNSIGNED NOT NULL,
period_id INT UNSIGNED NOT NULL,
date DATE NOT NULL,
state BOOL NOT NULL
)  ENGINE = MYISAM 
DEFAULT CHARACTER SET = utf8 
COLLATE = utf8_bin;

CREATE TABLE IF NOT EXISTS `lab_appointments`
(
appointment_id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
created DATETIME NOT NULL,
user_id INT UNSIGNED NOT NULL,
lab_id INT UNSIGNED NOT NULL,
period_id INT UNSIGNED NOT NULL,
date DATE NOT NULL,
class_size INT UNSIGNED NOT NULL,
comment TEXT NOT NULL,
lab_is_closed BOOL NOT NULL
) ENGINE = MYISAM 
DEFAULT CHARACTER SET = utf8 
COLLATE = utf8_bin;

是否可以为状态不为假的给定用户选择所有约会?我遇到的复杂情况是,对于存在的每个lab_closure_state,我可能不一定有lab_appointment个条目。 感谢

1 个答案:

答案 0 :(得分:0)

不是指对问题文本的严格答案,而是回答问题标题:

SELECT *
FROM lab_appointments root
LEFT OUTER JOIN lab_closure_states satellite 
    ON  satellite.lab_id = root.lab_id
    AND satellite.state = 0
WHERE 
    satellite.state_id IS NULL

上面显示的方法让您有机会在查询中链接多个卫星表,并通过在IS NULL语句中放置IS NOT NULLWHERE来构建复杂的过滤条件。