问题
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