Mysql - LIMIT by Percentage?

2019-01-19 15:51发布

Say I define an alias 'count' in my Select Query and I want to limit the amount returned to count / 5 (or 20% of the table).

How can I do this? Mysql doesn't seem to take anything but integers, not functions.

标签: mysql sql limit
3条回答
萌系小妹纸
2楼-- · 2019-01-19 16:12

Look into MySQL stored routines (procedures/functions)
http://dev.mysql.com/doc/refman/5.1/en/create-procedure.html

查看更多
我只想做你的唯一
3楼-- · 2019-01-19 16:14

the LIMIT clause can takes 2 arguments and must be integers constants.

you can try something like this

SET @skip=1; SET @numrows=(select count(*) div 5 from tbl );
PREPARE STMT FROM 'SELECT * FROM tbl LIMIT ?, ?';
EXECUTE STMT USING @skip, @numrows;
查看更多
爷的心禁止访问
4楼-- · 2019-01-19 16:23

Correct. The LIMIT clause takes an offset and a count of rows, not a percentage. You're thinking of Microsoft SQL Server, which supports SELECT TOP 20 PERCENT ... (note that neither LIMIT or TOP are specified in standard SQL).

I would do this in two queries:

SELECT COUNT(*) FROM MyTable WHERE ...conditions...

SELECT * FROM MyTable WHERE ...conditions... ORDER BY ...order... LIMIT ?

Replace the parameter ? with the count / 5.

You don't have to solve every problem in a single query.

查看更多
登录 后发表回答