如标题所示:如何正确编写此SQL语句?
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
如果单独执行选择和子选择,则工作正常。 但是只要我把它们放在一起就会出现以下错误:
Error: A subquery has returned not exactly one row.
SQLState: 21000
ErrorCode: -284
Position: 470
答案 0 :(得分: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”组。
答案 1 :(得分:0)
看起来你想要两个'count'聚合,这可能是这样的:
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)