Mysql - LIMIT by Percentage?

后端 未结 2 1352
日久生厌
日久生厌 2020-12-10 15:16

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 s

2条回答
  •  天涯浪人
    2020-12-10 15:46

    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.

提交回复
热议问题