2016-10-03 43 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