MySQL - 如果 select 子查询中的计数为空,则更改为 0
MySQL - if count in select subquery is null change to 0
我有以下查询:
select `jobs`.*,
(SELECT COUNT(user_jobs_application.id) as count FROM user_jobs_application
join job_shifts on job_shifts.id = user_jobs_application.job_shift_id
where job_shifts.jobs_id = jobs.id
and user_jobs_application.status = 1
group by user_jobs_application.users_id
) as entries
from `jobs` where `jobs`.`deleted_at` is null order by `id` desc limit 25 offset 0
select 中的子查询将给出 null 而不是 0。如果值为 [,我可以更改它吗? =17=]null 会显示 0?
从子查询中删除 group by
子句应该就足够了。无论如何都不需要它,因为它在您过滤的列上分组(它是需要的,那么我的意思是子查询可能 return 多行,这会产生运行时错误)。
select
j.*,
(
select count(*) as count
from user_jobs_application uja
join job_shifts js on js.id = uja.job_shift_id
where js.jobs_id = j.id and uja.status = 1
) as entries
from jobs j
where j.deleted_at is null
order by id desc limit 25 offset 0
您查询的其他更改:
据推测,user_jobs_application(id)
不可为空;如果是这样,count(*)
就足够了,而且比 count(user_jobs_application.id)
更有效
table 别名使查询更易于读写
我有以下查询:
select `jobs`.*,
(SELECT COUNT(user_jobs_application.id) as count FROM user_jobs_application
join job_shifts on job_shifts.id = user_jobs_application.job_shift_id
where job_shifts.jobs_id = jobs.id
and user_jobs_application.status = 1
group by user_jobs_application.users_id
) as entries
from `jobs` where `jobs`.`deleted_at` is null order by `id` desc limit 25 offset 0
select 中的子查询将给出 null 而不是 0。如果值为 [,我可以更改它吗? =17=]null 会显示 0?
从子查询中删除 group by
子句应该就足够了。无论如何都不需要它,因为它在您过滤的列上分组(它是需要的,那么我的意思是子查询可能 return 多行,这会产生运行时错误)。
select
j.*,
(
select count(*) as count
from user_jobs_application uja
join job_shifts js on js.id = uja.job_shift_id
where js.jobs_id = j.id and uja.status = 1
) as entries
from jobs j
where j.deleted_at is null
order by id desc limit 25 offset 0
您查询的其他更改:
据推测,
更有效user_jobs_application(id)
不可为空;如果是这样,count(*)
就足够了,而且比count(user_jobs_application.id)
table 别名使查询更易于读写