JOIN不显示所有行

时间:2011-12-27 17:28:16

标签: mysql join

我有以下查询。

SELECT WEEK(Review.created)                               AS Week,
       CONCAT(Employee.firstname, ' ', Employee.lastname) AS Name,
       AVG(Rating.scale)                                  AS Average
FROM   employees Employee
       LEFT JOIN reviews Review
         ON Employee.id = Review.reviewee_id
       LEFT JOIN ratings AS Rating
         ON Rating.id = Review.rating_id
WHERE  Employee.id IN ( 71, 72 )
GROUP  BY WEEK(Review.created),
          Employee.id
ORDER  BY WEEK(Review.created),
          Employee.id 

结果如下:

36, Employee1, 2.9091
37, Employee2, 3.5000
37, Employee1, 3.7143
38, Employee2, 4.2000
38, Employee1, 4.0000
39, Employee2, 2.0000
40, Employee2, 2.8333
40, Employee1, 3.8571
41, Employee1, 2.6667
43, Employee2, 2.5000
43, Employee1, 1.5714
44, Employee2, 3.8333
44, Employee1, 4.4000
45, Employee2, 3.2500
45, Employee1, 4.8571
46, Employee2, 2.1667
46, Employee1, 2.2000
48, Employee2, 2.6667
49, Employee2, 1.4000
49, Employee1, 3.5000
50, Employee2, 2.0000
50, Employee1, 1.5000
51, Employee2, 2.7143
51, Employee1, 2.7500

我需要的是即使他们没有那个星期的评级,也要退还员工。

所以前两行会返回

36, Employee1, 2.9091
36, Employee2, NULL

对此的任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

可能是因为查询中的分组导致您的结果被省略。尝试删除分组,看看会发生什么

来源

http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html

答案 1 :(得分:0)

将group by子句更改为

GROUP BY Employee.id, WEEK(Review.created)

现在看来,如果您在审核周首先进行分组,那么对该周没有评论的任何员工将首先分组为NULL(week(null) -> null)。