1

I want to set an array to a variable in order to use it in my queries in "IN" clause. The code below gives me an error back, so I am not sure if it is possible in mysql.

set @ids = (1,2,3,6);

select 
    sum(promotion_id IN @ids AND confirmed_at IS NOT NULL)
from blabla

I get different two differt results. Namely, find_in_set and IN(@ids) give me identical result but it differs from the one I get from IN(1,2,3):

set @voda_prom ='1483, 2396, 2395, 1887';

    SUM(FIND_IN_SET(promotion_id,@voda_prom) and confirmed_at IS NOT NULL)*1.0/ SUM(FIND_IN_SET(promotion_id,@voda_prom)) as p,
    SUM(promotion_id IN(1483,2396,2395,1887) and confirmed_at IS NOT NULL)*1.0/ SUM(promotion_id IN(1483,2396,2395,1887)) as p_check,
    SUM(promotion_id IN(@voda_prom) and confirmed_at IS NOT NULL)*1.0/ SUM(promotion_id IN(@voda_prom)) as p_1,

3 Answers 3

1

use find_in_set instead of in

set @ids = '1,2,3,6';
select 
    SUM(CASE WHEN FIND_IN_SET(promotion_id,@ids) AND confirmed_at IS NOT NULL THEN 1 ELSE 0 END)
from blabla

this function is just same as in_array in php

Sign up to request clarification or add additional context in comments.

4 Comments

No, it did not. The result is different from when i use IN(1,2,3..)
you mean its different from promotion_id in(1,2,3,6) or just promotion_id in(@ids)
find_in_set and IN(@ids) give me the same results but it is different from IN(1,2,3)
0

You can use like this:

SET @ids = '1, 2, 3, 6';
select 
    sum(`promotion_id` IN ( @ids)  AND `confirmed_at` IS NOT NULL)
from `blabla`

Comments

0
**You Have To Convert Array Into String First Each Element is Imploaded By , commma**


   $arr=array(1,2,3,6);
     $str_arr=implode(',',$arr);


    set @ids = '1,2,3,6';

    select 
        sum(promotion_id IN @ids AND confirmed_at IS NOT NULL)
    from blabla

Comments

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.