zoukankan      html  css  js  c++  java
  • 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;
  • 相关阅读:
    动态规划最后一击
    leetcode N-Queens I && N-Queens II
    leetcode Spiral Matrix
    leetcode Submission Details
    由网易云音乐到算法体会
    leetcode Rotate Image
    线性表之双链表
    线性表之循环单链表
    线性表之单链表
    [HDU] 1561 The more, The Better 树形DP加01分组背包
  • 原文地址:https://www.cnblogs.com/dkblog/p/1980783.html
Copyright © 2011-2022 走看看