2012-06-14 71 views
1

我正面临一种情况,需要帮助。我有两个表:mysql LEFT JOIN select results with limited results

用户:

  • user_idfnamelnameemail

user_timesheet:

  • time_iduser_idmonthstatedate

用户对时间与状态添加到user_time表=“不”,并在月底他们提交时间,这改变状态=“是”假设一个月JUNE 我想编写一个查询,它将使所有没有添加时间的用户和已添加时间但尚未提交给JUNE的用户。

这是我的查询。

SELECT user_timesheet.time_id, user_timesheet.user_id, 
    user_timesheet.month, user_timesheet.`state`, 
    `user`.user_id, `user`.fname, `user`.lname, 
    `user`.email 
FROM user LEFT JOIN 
    user_timesheet ON user.user_id=user_timesheet.user_id 
WHERE (
    user_timesheet.state = 'no' OR 
    user_timesheet.state IS NULL) 
AND (
    user_timesheet.month = 'june' OR 
    user_timesheet.month IS NULL) 
GROUP BY user.user_id 

结果带来谁已经在6月新增时间所有用户,而且已经提交了它,也从来没有谁补时到系统的用户,因为他们加入。但是,它并没有为上个月增加时间或提交时间的用户提供服务,但在六月份没有增加时间。

回答

0

代替(A = x或a为null)的where子句把你的过滤器在ON子句。这将删除不匹配的记录,但保留左连接的性质。

对待“不”的地位,不存在的行筛选出来的左连接:

SELECT user_timesheet.time_id, user_timesheet.user_id, 
     user_timesheet.month, user_timesheet.`state`, 
     `user`.user_id, `user`.fname, `user`.lname, 
     `user`.email 
    FROM user 
    LEFT JOIN user_timesheet 
    -- Eliminate users who have submitted 'no' 
    -- For June 
    ON user.user_id=user_timesheet.user_id 
    -- Turn 'no' status into null record 
    AND user_timesheet.state <> 'no' 
    AND user_timesheet.month = 'june' 
    -- If there is no row in user_timesheet 
    -- It means that 
    -- a) There was not any 
    -- b) There was a 'no' status 
WHERE user_timesheet.user_id is null 
GROUP BY user.user_id 

注:我不知道什么是MySQL的注释标记。这是 - 在Sql Server中,所以在尝试查询之前删除这些行。

+0

非常感谢你。请问如果我可能会问,这个<>在语句 –

+0

@ user1451414 <>中意味着什么意味着在标准sql中不等于'。欢迎您:-) –

+0

好,那么!=和<> –

0

首先创建一个匹配所有用户的userId的查询,该用户在指定的时间段内用“YES”状态添加时间=>您拥有所有“好”用户。那么你必须选择所有不在该列表中的用户。你可以使用一个不在,一个不存在的子查询或减号查询。

例如用未在:

SELECT user_timesheet.time_id, user_timesheet.user_id, user_timesheet.month, user_timesheet.`state`, `user`.user_id, `user`.fname, `user`.lname, `user`.email 
    FROM user LEFT JOIN user_timesheet ON user.user_id=user_timesheet.user_id 
where user.user_id not in (
    select user.user_id 
    from user inner join user_timesheet ON user.user_id=user_timesheet.user_id 
    where user_timesheet.state = 'yes' 
    AND user_timesheet.month = june 
) 
) 
+0

谢谢,你的答案确实有效 –

0
SELECT user_timesheet.time_id, user_timesheet.user_id, user_timesheet.month, user_timesheet.`state`, 
     `user`.user_id, `user`.fname, `user`.lname, `user`.email 
    FROM user 
    LEFT JOIN user_timesheet 
    ON user.user_id=user_timesheet.user_id 
    AND user_timesheet.month = 'june' AND user_timesheet.state = 'no' 
+0

AND user_timesheet.month ='june'AND user_timesheet.state ='no'将确保该月份是6月份并且未提交,因为no表示没有提交到月底的时间。 –