简体   繁体   English

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

[英]MySql Select count until find certain value

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

With simple count result will equal 5 简单计数结果将等于5

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

How I can count until find a certain value? 在找到某个值之前,我该如何计数?

For example: count until my_id is '222' with count result = 3 例如:计数直到my_id为'222'且计数结果= 3

Thank you! 谢谢!

That depends on the order, what do you mean by "until my_id is 222"? 这取决于顺序,“直到my_id为222”是什么意思?

You can make a query like this(or the opposite) but this will use the my_id field to determine who should be counted: 您可以像这样(或相反)进行查询,但这将使用my_id字段来确定应该计数的对象:

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

EDIT: Your question missing some crucial information, but maybe you meant this: 编辑:您的问题缺少一些关键信息,但也许您的意思是:

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)

This query is relying on the fact the only 1 record will match the inner query . 该查询所依据的事实是,只有1条记录将匹配内部查询。

SQLFiddle SQLFiddle

假设数字已排序

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM