为什么SQL在查询中使用count和count,*时会返回不同的结果

时间:2016-04-29 12:47:24

标签: sql

我有表attendanceemployeepayroll

出勤表:

Employee_ID  Clockin    Clockout
---------------------------------
1            08:00:00    18:00:00
2            08:00:00    18:00:00
3            08:00:00    18:00:00
4            08:00:00    18:00:00

员工表:

Employee_ID   Name       Employee_type
---------------------------------
1            Mary         Full-time
2            Peter        Full-time
3            John         Full-time
4            Henry        Full-time

这是我只得到1行的SQL查询

    SELECT *, COUNT(attendance.Clockin)
    FROM payroll
    LEFT JOIN attendance ON attendance.Employee_ID = payroll.Employee_ID
    LEFT JOIN employee ON employee.Employee_ID = payroll.Employee_ID
    WHERE employee.Employee_type = 'Full-time'

这是我获得更多行返回的SQL查询

    SELECT *
    FROM payroll
    LEFT JOIN attendance ON attendance.Employee_ID = payroll.Employee_ID
    LEFT JOIN employee ON employee.Employee_ID = payroll.Employee_ID
    WHERE employee.Employee_type = 'Full-time'

这两个查询之间的区别是什么?

2 个答案:

答案 0 :(得分:1)

哎呀,就是MySQL,不是吗?

使用

COUNT(attendance.Clockin)

您汇总数据。没有GROUP BY子句,因此只返回一行。

至于:

SELECT *, COUNT(attendance.Clockin)

,标准SQL不允许这样做,因为您选择的聚合列不是唯一的。例如,有许多名称,那么在那个返回的行中显示什么名称? MySQL已经解决了这个问题,它会返回一个任意可用的名称。

使用

SELECT *

但是,您没有聚合您的行。你可以按原样显示它们。

答案 1 :(得分:1)

SQL FIDDLE

以上小提琴有3个不同的查询;我扩展了您的第一个查询,以显示当您没有组时,mysql中会发生什么。

考虑:

--Yours without a group by, you get one row.  This is due to mySQL "Extended" group by  
SELECT *, COUNT(attendance.Clockin)
FROM payroll
LEFT JOIN attendance
ON attendance.Employee_ID = payroll.Employee_ID
LEFT JOIN employee
ON employee.Employee_ID = payroll.Employee_ID
WHERE employee.Employee_type = 'Full-time';

--Mine, with a group by, you get multiple rows
SELECT *, COUNT(attendance.Clockin)
FROM payroll P
LEFT JOIN attendance
ON attendance.Employee_ID = P.Employee_ID
LEFT JOIN employee
ON employee.Employee_ID = P.Employee_ID
WHERE employee.Employee_type = 'Full-time'
GROUP BY P.Employee_ID, clockin, clockout, employee_Type;

SELECT *
FROM payroll
LEFT JOIN attendance
ON attendance.Employee_ID = payroll.Employee_ID
LEFT JOIN employee
ON employee.Employee_ID = payroll.Employee_ID
WHERE employee.Employee_type = 'Full-time';

简单地说,如果你没有通过mySQL数据库引擎定义组,将从每列中选择一个值并返回它。由于第一个SQL statmeent具有聚合,因此扩展组by有效;而第二个SQL没有聚合,所以它只返回每一行。 From mySQL docs: The server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate.