将子查询添加到连接

时间:2016-10-03 20:58:04

标签: mysql

我一直在使用以下联接来吸引那些自愿担任各种项目职位的用户。

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 个答案:

答案 0 :(得分: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