开发者

Excluding results from SQL query based on entries in multiple tables

I have two tables in my database that look like this

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,
dat开发者_如何学Goe 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;

Is it possible to select all appointments for a given user where the state is not FALSE? The complication I have is that I may not necessarily have a lab_closure_state entry for each lab_appointment that exists. Thanks


Not to mean a strict answer to your question text but rather to answer the question header:

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

Approach shown above gives you an opportunity to link multiple satellite tables in your query and build complex filter criterias by simply placing IS NULL or IS NOT NULL in WHERE statement.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜