Count from a table, but stop counting at a certain number

前端 未结 3 1727
别跟我提以往
别跟我提以往 2021-01-18 08:13

Is there a way in MySQL to COUNT(*) from a table where if the number is greater than x, it will stop counting there? Basically, I only want to know

相关标签:
3条回答
  • 2021-01-18 08:54

    I can't think of anything. It looks to me like what you're doing exactly fulfils the purpose, and SQL certainly doesn't seem to go out of its way to make it easy for you to do this more succinctly.

    Consider this: What you're trying to do doesn't make sense in a strict context of set arithmetic. Mathematically, the answer is to count everything and then take the MIN() with 100, which is what you're (pragmatically and with good reason) trying to avoid.

    0 讨论(0)
  • 2021-01-18 08:59

    This works:

    select count(*) from ( select * from  stockinfo s limit 100 ) s
    

    but was not any faster (that I could tell) from just:

    select count(*) from stockinfo
    

    which returned 5170965.

    0 讨论(0)
  • 2021-01-18 09:05
    SELECT * FROM WhateverTable WHERE WhateverCriteria
    LIMIT 100, 1
    

    LIMIT 100, 1 returns 101th record, if there is one, or no record otherwise. You might be able to use the above query as a sub-query in EXIST clauses, if that helps.

    0 讨论(0)
提交回复
热议问题