1

我正在尝试编写一个 SQL 命令,该命令以个人表设备历史记录为每个人存储。当前设备不是 null devicex_mac。因此,device2_mac 可能是当前设备(device3_mac 为空)或 device1_max 可能是当前设备(device2_mac 和 device3_mac 都为空)。

**Person Table**            
id  device1_mac device2_mac device3_mac


**Device Table**        
mac   brand   model

有了上面的事实,我如何检测当前设备并 JOIN 两个表以获得以下结果。

**RESULT:**

BRAND   MODEL   COUNT
BRAND1  Model1  350000
BRAND1  Model2  700000
BRAND2  Model1  480000
4

2 回答 2

3

如果您想查看所有列的分布,您可以:

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通常会导致数据库忽略索引。

于 2013-06-25T10:36:50.500 回答
1

我假设任何时候只有一个设备列具有值。然后你可以这样做:

SELECT
   brand,
   model,
   COUNT(*)
FROM
  tblDevice 
  JOIN tblPerson ON
     tblDevice.mac = tblPerson.device1_mac OR
     tblDevice.mac = tblPerson.device2_mac OR
     tblDevice.mac = tblPerson.device3_mac
group by 
   brand, 
   model
于 2013-06-25T10:39:40.410 回答