Mysql Join显示包含或不包含匹配记录的所有记录

时间:2014-04-21 18:13:22

标签: mysql

我有两张桌子。一个用于员工,另一个用于评级。有些员工没有被评为其他员工。我正在尝试列出所有具有或不具有评级值的员工,并从最高评级中对其进行排序。

emp table

empid empName
--------------
1     John
2     Alex
3     Peter
4     Mary

Ratings table

ratingid | customerid | ratingvalue | empid
---------------------------------------------
1         1             4             1
2         6             2             1
3         4             3             3
4         5             5             4

预期产出:

empid  | empName   | avgrating | ratingcount
---------------------------------------------
1         John             3             2
2         Alex             0             0
3         Peter            3             1
4         Mary             5             1

我试过

SELECT *, round(AVG(ratingvalue ), 2) as avgrating, count(empid) as ratingcount 
FROM emp LEFT JOIN ratings ON emp.empid = ratings.empid ORDER BY `avgrating`
DESC

该查询不会产生我期望的结果。它只给了我一行。

提前致谢

2 个答案:

答案 0 :(得分:0)

需要group by并将空值合并为0。

SELECT EmpID, empName, 
  coalesce(round(AVG(ratingvalue ), 2),0) as avgrating, 
  coalesce(count(empid),0) as ratingcount 
FROM emp 
LEFT JOIN ratings 
  ON emp.empid = ratings.empid 
GROUP BY EmpID, EmpName
ORDER BY `avgrating`DESC

答案 1 :(得分:0)

我认为这就是你想要的。

 select 
   e.id, e.name, 
   avg(coalesce(t1.rating,0)) average_rating, 
   count(coalesce(t1.rating,0)) count_rating 
 from 
(select '1' id, 'John' name union all
select '2' id, 'Alex' name union all
select '3' id, 'Peter' name union all
select '4' id, 'Mary' name) e


left join (select '1' id, '1' customer_id, '4' rating, '1' emp_id union all
select '2' id, '6' customer_id, '2' rating, '1' emp_id union all
select '3' id, '4' customer_id, '3' rating, '3' emp_id union all
select '4' id, '5' customer_id, '5' rating, '4' emp_id) t1 on
  t1.emp_id = e.id
group by 
 e.id, 
 e.name

我刚刚为你的数据表提供了数据。你可以直接在mysql中运行它,它应该给你想要的。