0

I'm trying to get the top half of entries whose flag field equals 1. I tried using a variable to hold the limit value as in

set @v1:=(select ceil(count(*)/2) as top_half from my_table
where flagged=1);

select * from my_table where flagged=1 order by 21_day_probability limit @v1;

But this does not work. Any suggestions?

Thanks

1 Answer 1

1

As documented under SELECT Syntax:

The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants, with these exceptions:

  • Within prepared statements, LIMIT parameters can be specified using ? placeholder markers.

  • Within stored programs, LIMIT parameters can be specified using integer-valued routine parameters or local variables.

Therefore LIMIT parameters can never be user-defined variables. Your options, as indicated above, are to use either:

  1. prepared statements

    PREPARE stmt FROM '
      select * from my_table where flagged=1 order by 21_day_probability limit ?
    ';
    EXECUTE stmt USING @v1;
    DEALLOCATE PREPARE stmt;
    
  2. a parameter/local variable within a stored program:

    CREATE PROCEDURE foo(_l INT)
      select * from my_table where flagged=1 order by 21_day_probability limit _l
    ;
    CALL foo(@v1);
    
Sign up to request clarification or add additional context in comments.

7 Comments

OK now i need a way do do this without declaring a variable. Is this possible?
@user1893354: How do you mean? Using the second method above, one could CALL foo(123);.
but you would still need to declare the @v1 variable, wouldn't you?
in the last line 'CALL foo(@v1)'. I assume @v1 would need to be declared in order to do this
@user1893354: See my previous comment - "Using the second method above, one could CALL foo(123);".
|

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.