DROP TABLE IF EXISTS `log`;
CREATE TABLE `log` (
`log_id` bigint(20) NOT NULL auto_increment,
`device_ip` varchar(23) NOT NULL,
`severity` tinyint(1) NOT NULL,
PRIMARY KEY (`log_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE VIEW `k3` AS SELECT device_ip,count(CASE WHEN severity=3 THEN 1 ELSE NULL END) as s3 FROM log where 1=1 group by device_ip;
CREATE VIEW `k2` AS SELECT device_ip,count(CASE WHEN severity=2 THEN 1 ELSE NULL END) as s2 FROM log where 1=1 group by device_ip;
CREATE VIEW `k1` AS SELECT device_ip,count(CASE WHEN severity=1 THEN 1 ELSE NULL END) as s1 FROM log where 1=1 group by device_ip;
select k3.device_ip,k3.s3,k2.s2,k1.s1 from k3,k2,k1 where k3.device_ip=k2.device_ip and k2.device_ip=k1.device_ip order by k3.s3 desc,k2.s2 desc,k1.s1 desc;
说明:count(CASE WHEN severity=1 THEN 1 ELSE NULL END)是为了让count为0的记录也显示出来。
以上简化为一个带子查询的sql:
select k3.device_ip,k3.s3,k2.s2,k1.s1 from (SELECT device_ip,count(CASE WHEN severity=3 THEN 1 ELSE NULL END) as s3 FROM log where 1=1 group by device_ip) as k3,(SELECT device_ip,count(CASE WHEN severity=2 THEN 1 ELSE NULL END) as s2 FROM log where 1=1 group by device_ip) as k2,(SELECT device_ip,count(CASE WHEN severity=1 THEN 1 ELSE NULL END) as s1 FROM log where 1=1 group by device_ip) as k1 where k3.device_ip=k2.device_ip and k2.device_ip=k1.device_ip order by k3.s3 desc,k2.s2 desc,k1.s1 desc;