如果您想查看所有列的分布,您可以:
select d.brand, d.model, count(*)
from ((select id, device1_mac as mac
from person
) union all
(select id, device2_mac
from person
) union all
(select id, device3_mac
from person
)
) pd left outer join
devices d
on pd.mac = d.mac
where mac is not null
group by d.brand, d.model
如果最后一列包含您想要的信息,您可以:
select d.brand, d.model, count(*)
from person p left outer join
devices d
on coalesce(p.device3_mac, p.device2_mac, p.device1_mac) = d.mac
where mac is not null
group by d.brand, d.model
coalesce()
选择第一个非 NULL 值。
编辑:
如果问题是关于性能并且有一个索引devices(mac)
,那么我建议对第一个查询进行变体:
select d.brand, d.model, count(*)
from ((select id, device1_mac as mac
from person
where device2_mac is null and device1_mac is not null
) union all
(select id, device2_mac
from person
where device3_mac is null and device2_mac is not null
) union all
(select id, device3_mac
from person
where device3_mac is not null
)
) pd left outer join
devices d
on pd.mac = d.mac
where mac is not null
group by d.brand, d.model
函数或子句or
中的使用on
通常会导致数据库忽略索引。