• mysql从视图view简化到带子查询的sql


    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;
  • 相关阅读:
    java的枚举
    java解析XML的三种方法
    java静态代理
    java注释
    Jquery基础之DOM操作
    sql点滴43—mysql允许用户远程登陆
    js实现复制功能
    MVC ViewData和ViewBag
    Visual Studio 2013 Web开发新特性
    VisualStudio2013快捷键
  • 原文地址:https://www.cnblogs.com/dkblog/p/1980783.html
Copyright © 2020-2023  润新知