MySQL COUNT()返回0

时间:2013-08-12 21:53:23

标签: mysql sql count null

我有一个如下所示的查询:

SELECT
  app.application_id,
  j.job_number,
  j.job_id,
  j.job_title,
  j.job_city,
  j.job_state,
  p.person_id  AS candidate_id,
  p.first_name,
  p.last_name,
  app.start_date,
  ope1.percent_complete,
  MAX(CASE
      WHEN r.role_display_name = 'ENG - Recruiter' THEN
        (SELECT CASE WHEN COUNT(last_name) = 0 THEN
                   'Unassigned'
                 ELSE
                   COUNT(last_name)
                 END AS uname
           FROM users
           JOIN job_roles ON job_roles.user_id = users.user_id
          WHERE job_id = j.job_id
            AND role_id = r.role_id
        )
      ELSE '' END) AS role_3

我的问题是COUNT(last_name)不会返回0,因为没有返回记录,因此没有NULL的值。一切都有道理,但我已经尝试将其包装在IFNULL()ISNULL()中,但似乎没有一个能解决这个问题。如果没有记录,如何让它返回0?我需要COUNT()汇总中的另一个子查询吗?我真的不想使用另一个子查询......

1 个答案:

答案 0 :(得分:1)

如果正确理解了你想要的东西,可以尝试用这种方式重写

SELECT ...
      ,MAX(CASE WHEN r.role_display_name = 'ENG - Recruiter' 
                THEN COALESCE(NULLIF(
                (
                     SELECT COUNT(last_name) 
                       FROM users JOIN job_roles 
                         ON job_roles.user_id = users.user_id 
                      WHERE job_id = j.job_id 
                        AND role_id = r.role_id
                 ), 0), 'Unassigned')
                ELSE ''
           END) as role_3
       ...