1

As written in the title: How to write this SQL statement correctly?

   select 
    sl.switch_ip,
    sl.switch_name, 
    count(m.switch_ip) as macentries,
    (select arpentries from (select sl1.switch_ip, sl1.switch_name, count(ar.switch_ip) as arpentries 
        from my_switchlist sl1 
        left Join my_arptable ar on ar.switch_ip = sl1.switch_ip
        group by sl1.switch_ip,sl1.switch_name 
        order by sl1.switch_ip))
    from my_switchlist sl 
        left Join my_mactable m on m.switch_ip = sl.switch_ip
    group by sl.switch_ip,sl.switch_name 
    order by sl.switch_ip

The select and the sub-select work fine if they are executed separately. But as soon as I put them together I get the following error:

Error: A subquery has returned not exactly one row.
SQLState: 21000
ErrorCode: -284
Position: 470
4

2 回答 2

0

您的“my_switchlist,my_arptable”加入中可能有多个“sl1.switch_ip,sl1.switch_name”组。

select arpentries from (select sl1.switch_ip, sl1.switch_name, count(ar.switch_ip) as arpentries 
        from my_switchlist sl1 
        left Join my_arptable ar on ar.switch_ip = sl1.switch_ip
        group by sl1.switch_ip,sl1.switch_name 
        order by sl1.switch_ip)

上述查询不应返回多个结果,以便您在外部查询中使用其结果。所以可能有不止一个“sl1.switch_ip,sl1.switch_name”组。

于 2012-12-04T12:53:45.760 回答
0

看起来您想要两个“计数”聚合,这应该可以通过以下方式实现:

select
   macquery.switch_ip,
   macquery.switch_name,
   macquery.macentries,
   arpquery.arpentries
from
(
   select 
      sl.switch_ip as switch_ip,
      sl.switch_name as switch_name,  
      count(m.switch_ip) as macentries
   from my_switchlist sl 
   left outer join my_mactable m
   on m.switch_ip = sl.switch_ip
   group by
      sl.switch_ip,
      sl.switch_name 
) macquery

join

(
   select
      sl1.switch_ip as switch_ip,
      sl1.switch_name as switch_name,
      count(ar.switch_ip) as arpentries 
   from my_switchlist sl1 
   left outer join my_arptable ar
   on ar.switch_ip = sl1.switch_ip
   group by
      sl1.switch_ip,
      sl1.switch_name 
) arpquery

on  (macquery.switch_ip =  arpquery.switch_ip
    and  macquery.switch_name =  arpquery.switch_name)
于 2012-12-04T12:59:48.277 回答