我有一个表格任务
select
sts_id,
count(*) mycount
from
task
where
sts_id in (1, 8, 39)
group by sts_id;
输出:
sts_id count
1 1
8 1
39 1
我还有一个临时表,其中一列是sts_id 看起来像这样
sts_id
1
8
39
40
41.
我正在尝试为两个表添加左连接
select
in_list.sts_id,
count(*) mycount
from
task
left outer join
in_list
on task.sts_id = in_list.sts_id
group by sts_id;
获得ab / p喜欢
1 1
8 1
39 1
40 0
41 0..
我收到了一个含糊不清的列错误。
答案 0 :(得分:2)
您正在以错误的方式使用left join
(在左侧,它必须是包含您要显示的所有行的表)。
Count (task.sts_id)
在该表上没有出现的行上获得0
select
in_list.sts_id,
count(task.sts_id) mycount
from
in_list
left outer join
task
on in_list.sts_id = task.sts_id
AND task.sts_id in (1, 8, 39) -- Thanks Matt.
group by in_list.sts_id;
答案 1 :(得分:1)
您缺少GROUP BY
子句中的表别名。
但是,您需要的结果表明您需要更改连接逻辑:起始表应为in_list
,而task
应位于左外连接中:
select ...
from in_list
left outer join task
答案 2 :(得分:1)
select
in_list.sts_id,
coalesce(count(task.sts_ID),0) mycount --changed this line
from
task
right outer join --changed this line
in_list
on task.sts_id = in_list.sts_id
group by in_list.sts_id; -- changed this line
<强>理由:强>
答案 3 :(得分:-1)
我通过此查询获得了答案
select t2.sts_id, count(t.sts_id)
from task t, in_list t2
where t2.sts_id = t.sts_id(+)
group by t2.sts_id
谢谢,