在MySQl中,假设有两个数据表Employee(E,雇员表)、Recorde(R,考勤表),以E.id=R.eid相连。现在要找出本月迟到超过三次的员工有多少人。
可能首先想到的SQL语句象这样:
select count(*) from Employee E,Recorde R where E.id=R.eid and ...(本月迟到超过三次)
但是得到的数据可能是错误的
修改为类似这样:
select count(E.id) from Employee E left join Recorde R on E.id=R.eid where ...(本月迟到超过三次)
是和上面的数据一模一样,我还是认为你可能错了
为什么我一口咬定你两次可能错了?你把 count(*) , count(E.id) 之类换成 * 试试看,找出的数据也许比上面的求出的得数少吧?
问题在于可能有些雇员本月没有考勤记录,难道不会有一个月的长假或者出差?
正确的做法是用 count(DISTINCT E.id)
如下:
select count(DISTINCT E.id) from Employee E,Recorde R where E.id=R.eid and ...(本月迟到超过三次)