MySql选择计数直到找到一定的值

时间:2018-10-08 10:49:12

标签: mysql count

id  number my_id
 1    1     789  
 1    2     645
 1    3     222
 1    4     544
 1    5     155

简单计数结果将等于5

SELECT COUNT(id) AS count FROM table WHERE id = 1 

在找到某个值之前我该如何计数?

例如:计数直到my_id为'222'且计数结果= 3

谢谢!

2 个答案:

答案 0 :(得分:2)

这取决于顺序,“直到my_id为222”是什么意思?

您可以像这样(或相反)进行查询,但这将使用my_id字段来确定应该对谁进行计数:

SELECT count(id) as count
FROM YourTable
WHERE id = 1 AND my_id <= 222

编辑:您的问题缺少一些关键信息,但也许您是这样想的:

SELECT COUNT(t.id) as count
FROM YourTable t
WHERE t.id = 1
  AND t.number <= (SELECT number FROM YourTable s
                   WHERE s.id = 1 and S.my_id = 222)

此查询所依据的事实是,只有1条记录将与内部查询匹配。

SQLFiddle

答案 1 :(得分:0)

假设数字已排序

select count(*) from t where `number`<=(select `number` from t where my_id=222)