我对SQL相当陌生,请原谅我的无知,或者我在这里问一个基本问题。我想要做的是让我的桌子返回0值,如果出口在最后一天没有创建作业。我使用的代码是:
SELECT public.outlets.title AS "Outlet",
COUNT(public.outlets.id) AS "Assignment Count"
FROM public.assignments
JOIN public.users
ON public.users.id=public.assignments.creator_id
LEFT JOIN public.outlets
ON public.outlets.id = public.users.outlet_id
WHERE public.outlets.dispatch_enabled = 'True'
AND DATE(public.assignments.created_at) = DATE(CURRENT_TIMESTAMP- interval '1 day')
GROUP BY public.outlets.title
HAVING count(public.outlets.id) = 0
ORDER BY public.outlets.title ASC
我已经尝试过COALESCE,但说实话,我并不是很了解它,知道我是否正确实施了它。按照目前的情况,我使用的当前代码正在给我" NO ROWS RETURNED"。我试过把我的where子句的各个部分都拿出来看看这是否会有所帮助。任何帮助将不胜感激!!
答案 0 :(得分:0)
您需要使用要保留所有行的表启动left join
。
SELECT o.title AS "Outlet", COUNT(*) AS "Assignment Count"
FROM public.outlets o LEFT JOIN
public.users u
ON o.id = u.outlet_id LEFT JOIN
public.assignments a
ON u.id = a.creator_id AND
DATE(a.created_at) = DATE(CURRENT_TIMESTAMP- interval '1 day')
WHERE o.dispatch_enabled = 'True'
GROUP BY o.title
HAVING count(*) = 0
ORDER BY o.title ASC;
注意:
public.outlets
开始,因为它定义了您要保留的行(SELECT o.title
)。LEFT JOIN
。assignments
上的条件需要在ON
子句而不是WHERE
子句中。COUNT(*)
更容易输入。答案 1 :(得分:0)
您是否在寻找具有分配数量的奥特莱斯?因为那时我觉得你想要网点成为" FROM"和左边的联接而不是相反的方式。
SELECT public.outlets.title AS "Outlet",
COUNT(public.assignments.id) AS "Assignment Count"
FROM public.outlets
JOIN public.users
ON public.outlets.id = public.users.outlet_id
LEFT JOIN public.assignments
ON public.users.id=public.assignments.creator_id
AND DATE(public.assignments.created_at) = DATE(CURRENT_TIMESTAMP-interval '1 day')
WHERE public.outlets.dispatch_enabled = 'True'
GROUP BY public.outlets.title
HAVING count(public.assignments.id) = 0
ORDER BY public.outlets.title ASC
答案 2 :(得分:0)
您可以将WHERE条件的一部分移动到LEFT JOIN,我也认为您必须切换表的顺序。最后,您必须计算连接左侧表格上的字段,可能使用distinct:
select
public.outlets.title AS "Outlet",
COUNT(DISTINCT public.assignments.id) AS "Assignment Count"
from
public.outlets left join public.users
ON public.outlets.id = public.users.outlet_id
left join public.assignments
ON (
public.users.id=public.assignments.creator_id
AND DATE(public.assignments.created_at) = DATE(CURRENT_TIMESTAMP- interval '1 day')
)
where
public.outlets.dispatch_enabled = 'True'
group by
public.outlets.title
having
count(public.outlets.id) = 0
order by
public.outlets.title ASC
答案 3 :(得分:0)
很可能问题出在那些行
LEFT JOIN public.outlets
ON public.outlets.id = public.users.outlet_id
WHERE public.outlets.dispatch_enabled = 'True'
要求public.outlets.dispatch_enabled
不为空,以便有效地将LEFT JOIN public.outlets
转换为INNER。因此不存在count(public.outlets.id) = 0
的行。将其重构为
LEFT JOIN public.outlets
ON public.outlets.id = public.users.outlet_id
AND public.outlets.dispatch_enabled = 'True'