2013-02-16 58 views
1

我想一個額外層添加到我的SQL查詢,看起來像這樣:增加一個額外的條件,SQL查詢

SELECT 
    COUNT(*) totalCount 
FROM 
    ts_room 
WHERE 
    NOT EXISTS (
    SELECT 1 
    FROM ts_roompref 
     JOIN ts_request 
     ON ts_roompref.request_id = ts_request.id 
     AND day_id = 1 
     AND period_id = 1 
    WHERE 
     ts_room.id = ts_roompref.room_id) 

我想它做的是檢查一排匹配request.id不存在於名爲ts_allocation的表中。這是我迄今爲止嘗試的,但它似乎並沒有工作:

SELECT 
    COUNT(*) totalCount 

FROM 
    ts_room 

WHERE 
    NOT EXISTS (
    SELECT 1 
    FROM ts_roompref 
     JOIN ts_request 
     ON ts_roompref.request_id = ts_request.id 
     AND day_id = 1 
     AND period_id = 1 
    WHERE 
     ts_room.id = ts_roompref.room_id) 

AND NOT EXISTS (
    SELECT 1 
    FROM ts_roompref 
     JOIN ts_allocation 
     ON ts_roompref.request_id = ts_allocation.request_id 
     AND ts_allocation.status = "Allocated" 
    WHERE 
     ts_room.id = ts_roompref.room_id) 
) 

任何想法?我在這裏包含了我的SQL小提琴:http://sqlfiddle.com/#!2/4540d/2

回答

1

我認爲問題與使用別名有關:一旦我將別名添加到查詢表中,查詢就會運行並返回一些值(link to your modified sqlfiddle):

SELECT COUNT(*) totalCount 
FROM ts_room rm 
WHERE 
NOT EXISTS (
    SELECT 1 
    FROM ts_roompref rp 
    JOIN ts_request rq ON rp.request_id = rq.id AND day_id = 1 AND period_id = 1 
    WHERE rm.id = rp.room_id) 
AND NOT EXISTS (
    SELECT 1 
    FROM ts_roompref rp 
    JOIN ts_allocation a ON rp.request_id = a.request_id AND a.status = "Allocated" 
    WHERE rm.id = rp.room_id)