0

I have a query that uses a variable in its where clause:

SET @id = 1;

SELECT  
    id,
    value
FROM myTable
WHERE id = @id;

I would like to run the query for @id values 1 through 100, and then union (or somehow combine) all the loop results into one result set. Is this possible in MySQL, and if so, what is a good approach?

2 Answers 2

1

Why would use use a variable for this? Just use a simple where clause:

select id, value
from myTable
where id between 1 and 100;

If, instead, you really want the first 100 rows by id, then use order by and limit:

select id, value
from myTable
order by id
limit 100;
Sign up to request clarification or add additional context in comments.

2 Comments

The query is simplified example of a more complex query that wouldn't work with this fix
@bsapaka . . . Ask another question that is more representative of what you need.
0

Just use a subquery to get the variable.

And put the where outside

SELECT *
FROM 
    (
    SELECT  
        @rownumber := if(@rownumber, @rownumber + 1, @rownumber + 1)  AS id,
        value
    FROM myTable
    CROSS JOIN (select @rownumber := 0) r
    ) as T
WHERE id < 100;

10 Comments

the order of evaluation is not guarenteed and this can cause problems with using variables in a select query. it is expressly recommended to not do
@JohnRuddell Im not 100% sure about this issue. what I found is something like this @rownumber := if(@rownumber, @rn + 1, @rn + 1) AS id, fix it?
you should read their docs on this and read the part with the order of evaluation
Yes, I read it before. What is the part explaining this problem?
search for the part where it talks about the order of evaluation
|

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.