MariaDB LIMIT statement brings more than limit

烂漫一生 提交于 2021-01-29 09:24:45

问题


I have 10,000 users on registrations table and want to limit this query to 3500 users from my application. But when I investigate the logs , sometimes it counts more than 3500. I can not understand why that query returns more than limit:

select  count(*)
    from  registrations
    where  (selectedtime IS NULL
       AND  expirationtime < NOW()
           )
    LIMIT  3500;

I tried manually on DB and saw sometimes more than 3500


回答1:


Your query only returns 1 row, which is less than 3500.

If you want to limit the number of rows that are being counted, you need to put that in a subquery.

SELECT COUNT(*)
FROM (
    SELECT 1
    FROM registrations
    WHERE selectedtime IS NULL AND expirationtime < NOW()
    LIMIT 3500) AS x



回答2:


A SELECT statement with COUNT returns the number of rows retrieved by the SELECT statement.

For performance reasons, the desired result is to limit that count. Including a LIMIT clause in the SELECT statement will not work since it only restricts the number of rows returned, which is always one.

The solution, what I call “Limited-Count”, is done by limiting a non-count SELECT statement and wrapping it in COUNT(*).

For example: If your count statement looks like

select count(*) from registrations where (selectedtime IS NULL AND expirationtime < NOW()) LIMIT 3500;

You can limit the results by replacing the query into:

SELECT COUNT(*) AS total
FROM (
    SELECT 1
    FROM registrations
    WHERE selectedtime IS NULL AND expirationtime < NOW()
    LIMIT 3500) AS x

If you need to know how many rows your non-count SELECT statement would have returned without the LIMIT, you could use the information function, FOUND_ROWS(). It will fetch the total rows number without running the statement again.




回答3:


This does what you thought you were doing:

select  count(*)
    from  registrations
    where  (selectedtime IS NULL
       AND  expirationtime < NOW()
           )
    LIMIT ROWS EXAMINED 3500;

(Available since MariaDB 5.5.21 - see https://mariadb.com/kb/en/library/limit-rows-examined/ )



来源:https://stackoverflow.com/questions/56996085/mariadb-limit-statement-brings-more-than-limit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!