2

I have a query SELECT * FROM grades WHERE userid = 4123;

I want to limit this query

I have a query SELECT * FROM grades WHERE userid = 4123 LIMIT(2);

This works great but if I want this limit to be dynamic from another query.

SELECT COUNT(id) FROM count_table WHERE course = 131;

doing this gives me a syntax error

SELECT * FROM grades WHERE userid = 4123 LIMIT (SELECT COUNT(id) FROM count_table WHERE course = 131);

if this is not possible at all, then is there an alternative way to achieve this?

please help.!

5
  • 'LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants, ' - dev.mysql.com/doc/refman/8.0/en/select.html. Try dynamic sql. Commented Jun 21, 2019 at 11:57
  • thanks, is there any alternate way ? Commented Jun 21, 2019 at 12:25
  • Possible duplicate of How to write a SQL query with dynamic LIMIT Commented Jun 21, 2019 at 12:32
  • What version of MySQL? It may be possible in MySQL 8.x. Commented Jun 21, 2019 at 12:37
  • By the way, using LIMIT without ORDER BY makes little sense. Commented Jun 21, 2019 at 12:39

1 Answer 1

0

You can do it in MySQL 8.x using the ROW_NUMBER() function.

Assuming you order the rows by some column (I guessed the column ID... change it as needed), you can do:

select
  g.*
from (
  select
    *,
    row_number() over(order by id) as rn -- change ordering as needed
  from grades
  ) g
join (
  SELECT COUNT(id) as cnt FROM count_table WHERE course = 131
) c on g.rn <= c.cnt
Sign up to request clarification or add additional context in comments.

2 Comments

sql <e>Query: select g.* from ( select *, row_number() over(order by id) as rn from grades ) g join ( SELECT COUNT(id) as cn... Error Code: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(order by id) as rn from grades ) g join ( SELECT C' at line 6
Check you MySQL version. It seems you don't have 8.x yet.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.