MYSQL |在COUNT()中使用子查询时出现语法错误

时间:2014-12-16 05:37:24

标签: mysql sql select count group-by

SELECT 
E.`employee_id`,
E.`full_name`,
LE.`no_of_leaves` AS AllocatedLeaves,
MLLT.`leave_type` AS LeaveTypeName,
COUNT(SELECT * FROM leave_approval WHERE employee_id = 1) AS TotalLeavesTaken
FROM employee E
INNER JOIN leave_entitlement LE
ON E.`employee_id` = LE.`employee_id`
INNER JOIN `ml_leave_type` MLLT
ON MLLT.`ml_leave_type_id` = LE.`ml_leave_type_id`
LEFT JOIN leave_approval LA
ON E.`employee_id` = LA.`employee_id`
LEFT JOIN leave_application LAPP
ON LAPP.`application_id` = LA.`leave_application_id`
LEFT JOIN ml_leave_type MLLTLA
ON MLLTLA.`ml_leave_type_id` = LAPP.`ml_leave_type_id`

我在计数附近遇到语法错误,但我试图找出语法错误,我找不到任何?

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'select * from leave_approval where employee_id = 1) AS TotalLeavesTaken
from emp' at line 6

这真的是语法错误吗?还是我在这里缺少什么?

4 个答案:

答案 0 :(得分:1)

变化

COUNT(SELECT * FROM leave_approval WHERE employee_id = 1) AS TotalLeavesTaken

 (SELECT count(*) FROM leave_approval WHERE employee_id = 1) AS TotalLeavesTaken

答案 1 :(得分:1)

这一行:

COUNT(SELECT * FROM leave_approval WHERE employee_id = 1) AS TotalLeavesTaken

不正确。如果不将select *子查询放在括号中,则无法对其进行计数,但即使这样,您也需要group by和其他逻辑。更好的方法是:

(Select count(*) from leave_approval where employee_id = 1) AS TotalLeavesTaken

答案 2 :(得分:1)

在您的情况下,无需使用子查询来查看查询

试试这个:

SELECT E.employee_id, E.full_name, LE.no_of_leaves AS AllocatedLeaves,
       MLLT.leave_type AS LeaveTypeName,
       SUM(CASE WHEN LA.employee_id = 1 THEN 1 ELSE 0 END) AS TotalLeavesTakenByEmplyeeNo1
FROM employee E
INNER JOIN leave_entitlement LE ON E.employee_id = LE.employee_id
INNER JOIN `ml_leave_type` MLLT ON MLLT.ml_leave_type_id = LE.ml_leave_type_id
LEFT JOIN leave_approval LA ON E.employee_id = LA.employee_id
LEFT JOIN leave_application LAPP ON LAPP.application_id = LA.leave_application_id
LEFT JOIN ml_leave_type MLLTLA ON MLLTLA.ml_leave_type_id = LAPP.ml_leave_type_id
GROUP BY E.employee_id;

答案 3 :(得分:0)

尝试此查询

SELECT E.`employee_id`,E.`full_name`,LE.`no_of_leaves` AS AllocatedLeaves,MLLT.`leave_type` AS LeaveTypeName,
SUM( CASE WHEN LA.employee_id = '1' THEN 1 ELSE 0 END ) as TotalLeavesTaken
FROM employee E
INNER JOIN leave_entitlement LE
ON E.`employee_id` = LE.`employee_id`
INNER JOIN `ml_leave_type` MLLT
ON MLLT.`ml_leave_type_id` = LE.`ml_leave_type_id`
LEFT JOIN leave_approval LA
ON E.`employee_id` = LA.`employee_id`
LEFT JOIN leave_application LAPP
ON LAPP.`application_id` = LA.`leave_application_id`
LEFT JOIN ml_leave_type MLLTLA
ON MLLTLA.`ml_leave_type_id` = LAPP.`ml_leave_type_id`

只有你必须将COUNT(SELECT * FROM leave_approval WHERE employee_id = 1)替换为SUM(CASE WHEN LA.employee_id ='1'那么1 ELSE 0 END)

非常感谢,试试这个,因为我尝试了这个查询,它会给你完美的结果