zoukankan      html  css  js  c++  java
  • mysql 练习笔记

    从一个数据表中找出连续n条满足条件的记录

    例子demo 从数据表中找出连续三条或者三次以上分数超过80分的记录

    MariaDB [testdatabase]> select * from class;
    +----+-----------+---------+-------+
    | id | classname | teacher | grade |
    +----+-----------+---------+-------+
    |  0 | 101       | peter   |    85 |
    |  1 | 102       | john    |    86 |
    |  2 | 103       | tom     |    87 |
    |  3 | 104       | mango   |    88 |
    |  4 | 101       | peter   |    65 |
    |  5 | 106       | peter   |    95 |
    |  6 | 105       | haden   |    96 |
    |  7 | 107       | james   |    77 |
    |  8 | 108       | jakie   |    88 |
    |  9 | 109       | tom     |    85 |
    | 10 | 112       | mango   |    76 |
    | 11 | 113       | jula    |    77 |
    | 12 | 114       | john    |    78 |
    +----+-----------+---------+-------+
    SQL语句如下
    select * from class where id in (
      select DISTINCT n1.id from class n1,class n2,class n3 where
         (n1.grade>80 and n2.grade>80 and n3.grade>80 and
         ((n1.id + 1= n2.id and n2.id +1 = n3.id) OR
          (n1.id-1=n2.id and n1.id+1=n3.id) OR
          (n1.id-1=n2.id and n1.id-2=n3.id) )
         ) order by n1.id )

    输出结果

    +----+-----------+---------+-------+
    | id | classname | teacher | grade |
    +----+-----------+---------+-------+
    |  0 | 101       | peter   |    85 |
    |  1 | 102       | john    |    86 |
    |  2 | 103       | tom     |    87 |
    |  3 | 104       | mango   |    88 |
    +----+-----------+---------+-------+
  • 相关阅读:
    静态检查lua语法工具luacheck
    centos7系列:
    git submodule 教程
    CENTOS 7 安装redis
    python基本语法:
    彻底理解lib和dll
    C++语言的设计与演化(空白):
    《Effective C++》 目录:
    C++进阶书籍(转)
    学习的心态(转)
  • 原文地址:https://www.cnblogs.com/mangojun/p/11492065.html
Copyright © 2011-2022 走看看