一个动作表(actions),记录每一次卖出苹果的数量,有先后顺序。id小的先卖出。CREATE TABLE `actions` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`amount` int(11) DEFAULT NULL,
`user_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=24 DEFAULT CHARSET=utf8有如下的记录。
+----+--------+---------+
| id | amount | user_id |
+----+--------+---------+
| 1 | 23 | 1 |
| 2 | 24 | 2 |
| 3 | 43 | 3 |
| 4 | 23 | 4 |
| 5 | 12 | 5 |
| 6 | 15 | 6 |
| 7 | 24 | 7 |
| 8 | 25 | 8 |
| 9 | 35 | 9 |
| 10 | 22 | 10 |
| 11 | 32 | 11 |
| 12 | 15 | 12 |
| 13 | 21 | 13 |
| 14 | 32 | 14 |
| 15 | 34 | 15 |
| 16 | 56 | 16 |
| 17 | 11 | 17 |
| 18 | 9 | 18 |
| 19 | 2 | 19 |
| 20 | 10 | 20 |
| 21 | 15 | 21 |
| 22 | 46 | 22 |
| 23 | 72 | 23 |
+----+--------+---------+怎么找到 前100个苹果是那些人买的?
`id` int(11) NOT NULL AUTO_INCREMENT,
`amount` int(11) DEFAULT NULL,
`user_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=24 DEFAULT CHARSET=utf8有如下的记录。
+----+--------+---------+
| id | amount | user_id |
+----+--------+---------+
| 1 | 23 | 1 |
| 2 | 24 | 2 |
| 3 | 43 | 3 |
| 4 | 23 | 4 |
| 5 | 12 | 5 |
| 6 | 15 | 6 |
| 7 | 24 | 7 |
| 8 | 25 | 8 |
| 9 | 35 | 9 |
| 10 | 22 | 10 |
| 11 | 32 | 11 |
| 12 | 15 | 12 |
| 13 | 21 | 13 |
| 14 | 32 | 14 |
| 15 | 34 | 15 |
| 16 | 56 | 16 |
| 17 | 11 | 17 |
| 18 | 9 | 18 |
| 19 | 2 | 19 |
| 20 | 10 | 20 |
| 21 | 15 | 21 |
| 22 | 46 | 22 |
| 23 | 72 | 23 |
+----+--------+---------+怎么找到 前100个苹果是那些人买的?
from (
select id,userid
from tb A
where not exists (select 1 from tb A.userid=userid and A.id>id)
)T
order by id desc
limit 100
select 1 from tb A.userid=userid and A.id>id 这里少 where ,修正语法后。执行的结构还是不对。希望能够输出思路。如果写出sql就更好了。
from actions t
where 100>(select SUM(amount) From actions where id<t.id)
from actions t
where 100>(select SUM(amount) From actions where id<t.id)---这句执行过程是啥
select *
from actions
where id <= (
--将正好买到100个苹果的人找出来
select id from actions t
where (select sum(amount) from actions where id <= t.id) >= 100
and (select sum(amount) from actions where id <= t.id-1) < 100);
from actions t
where 100>(select SUM(amount) From actions where id<t.id 顶