2

如何从having子句中的子选择中引用网络列?

select distinct c.id, c.name,
(
select count(cm.id) cnt
from
company_mapping cm
where
cm.company_id_source = c.id
or
cm.company_id_target = c.id
) network
from company c
where
c.name like 'foobar%'
group by c.id, c.name
having network > 1

ORA-00904:“网络”:标识符无效。如果我省略最后一行,它会按预期工作,但我只对 network > 1 的行感兴趣。

4

4 回答 4

9

您无法访问select在或 group by中定义的字段。havingwhere

sql运算符的顺序如下:

1.FROM clause
2.WHERE clause
3.GROUP BY clause
4.HAVING clause
5.SELECT clause
6.ORDER BY clause 

这就是为什么你可以使用networkinorder by而不是 in 之前的运算符select

于 2013-05-15T08:42:33.127 回答
3

你想做这样的事情吗?

select c.id
      ,c.name
      ,count(*) 
      ,count(s.company_id_source) as num_sources
      ,count(t.company_id_target) as num_targets
  from company              c
  left join company_mapping s on(s.company_id_source = c.id)
  left join company_mapping t on(t.company_id_target = c.id)
 where c.name like 'foobar%'  
 group 
    by c.id
      ,c.name
having count(s.company_id_source) > 1
    or count(t.company_id_target) > 1;

编辑:下面的新查询以响应评论。查询现在返回:匹配“Foobar”的所有公司,无论它们在表 company_mapping 中是否有关联行,以及:

  • num_sources:company_mapping 中以公司为来源的行数。
  • num_targets:company_mapping 中以公司为目标的行数。
  • num_mappings:company_mapping 中“连接”的编号(源或目标)

.

select c.id
      ,c.name
      ,count(s.company_id_source) + count(t.company_id_target)   as num_mappings
      ,count(s.company_id_source) as num_sources
      ,count(t.company_id_target) as num_targets
  from company              c
  left join company_mapping s on(s.company_id_source = c.id)
  left join company_mapping t on(t.company_id_target = c.id)
 where c.name like 'foobar%'  
 group 
    by c.id
      ,c.name;
于 2013-05-15T09:17:10.887 回答
3

Ronnis 是在正确的道路上,但查询实际上应该更简单。请尽量避免 select inside select,因为它在 99% 的情况下都是性能杀手。

select c.id
,      c.name
,      count(*) network
from   company c
join   company_mapping cm on c.id in (cm.company_id_source, cm.company_id_target)
where  c.name like 'foobar%'
group by c.id, c.name
having count(*) > 1
于 2013-05-15T09:25:31.510 回答
2

首先,您不能在同一个查询中使用distinctand 。group by这只是多余的,你是对的,我不知道为什么oracle不抛出异常。

其次,别名在与查询相同的级别上是不知道的。您应该将其包含在外部查询中。

select id, name, network
from (
    select c.id, c.name,
      (
      select count(cm.id) cnt
      from
      company_mapping cm
      where
      cm.company_id_source = c.id
      or
      cm.company_id_target = c.id
      ) network
    from company c
    where
    c.name like 'foobar%'
    group by c.id, c.name
)
WHERE network > 1;
于 2013-05-15T08:38:09.707 回答