具体需求如下:

  name   age   order_by
    a     15      1
    b     20      5
    c     16      4
    d     18      3
    e     22      6
查找按order_by倒序排列后age之和小于40的多行

解决方案 »

  1.   

    改:age之和小于60的多行
    结果如下
    name age order_by
       e   22   6
       b   20   5
       c   16   4
      

  2.   

    SELECT A.* FROM TT A
    INNER JOIN
    (SELECT name FROM TT GROUP BY NAME HAVING SUM(age)<=60 ) B
    ON A.NAME=B.NAME ORDER BY A.order_by LIMIT 3
      

  3.   


    select a.* from
    tb a
    where 60>=(select sum(age) from tb where order_by>=a.order_by)
    order by a.order_by desc;
      

  4.   

    select *
    from 表 a
    where (select sum(age) from 表 where order_by<=a.order_by)<=40;
      

  5.   

    mysql> select * from `表`;
    +------+------+----------+
    | name | age  | order_by |
    +------+------+----------+
    | a    |   15 |        1 |
    | b    |   20 |        5 |
    | c    |   16 |        4 |
    | d    |   18 |        3 |
    | e    |   22 |        6 |
    +------+------+----------+
    5 rows in set (0.00 sec)mysql> select *
        -> from `表` a
        -> where (select sum(age) from `表` where order_by<=a.order_by)<=60;
    +------+------+----------+
    | name | age  | order_by |
    +------+------+----------+
    | a    |   15 |        1 |
    | c    |   16 |        4 |
    | d    |   18 |        3 |
    +------+------+----------+
    3 rows in set (0.00 sec)mysql>
    mysql>