2016-10-03 73 views
0

我一直在使用下面的連接來拉動自願參與各種項目位置的用戶行。將子查詢添加到連接

SELECT p.id, up.position_id, title, max_vol, current_datetime, IF(up.id IS NULL, "0", "1") volunteered 
    FROM positions AS p 
    LEFT JOIN users_positions AS up 
    ON p.id = up.position_id 
    AND up.user_id = 1 
    AND up.calendar_date = '2016-10-03' 
    WHERE 
     p.project_id = 1 
     AND p.day = 1 

...但在功能的變化中,我現在必須考慮最新編輯項目的日期。在另一個查詢,我解決它像這樣

SELECT * 
FROM positions 
WHERE 
    current_datetime = (SELECT MAX(current_datetime) 
     FROM positions 
     WHERE 
      project_id = 1 AND day = 1) 

的正常工作,但現在我也必須納入符合最新的日期時間,其左聯接查詢行的回報。

我只是似乎無法包圍我的頭。有什麼建議麼?謝謝。

回答

1

使用子查詢,例如:

SELECT 
    p.id, 
    up.position_id, 
    title, 
    max_vol, 
    current_datetime, 
    IF(up.id IS NULL, 
    "0", 
    "1") volunteered  
FROM 
    ( SELECT 
    *  
    FROM 
    positions  
    WHERE 
    current_datetime = (
     SELECT 
     MAX(current_datetime)     
     FROM 
     positions     
     WHERE 
     project_id = 1    
     AND day = 1  
    )  
) AS p  
LEFT JOIN 
    users_positions AS up    
    ON p.id = up.position_id    
    AND up.user_id = 1    
    AND up.calendar_date = '2016-10-03'   
WHERE 
    p.project_id = 1     
    AND p.day = 1 
+0

我敢肯定,我想在這之前我張貼,但得到了一個錯誤。雖然這很有效。謝謝。 – user3442612