简体   繁体   中英

SELECT statement with where clause IN is not reading variable in MySQL

I'm running SELECT statement (database MySQL version 5.5.27 under Windows 7) with variable in WHERE clause. It supposed to return 6 records, but it doesn't. Below is a simple test code.

-- Test-I
SET @group_saids := (SELECT REPLACE(
                                    '''ClicPlan - España|ClicPlan - Francia|ClicPlan - UK|ClicPlan - Belgique|ClicPlan - Argentina|Clicplan - Turkey'''
                                    ,'|',"','") as aids_list from dual);

select @group_saids from dual;


select sd.aid
FROM said_aid sd
where sd.said in (@group_saids);

-- No records selected;

-- Test-II

select sd.aid
FROM said_aid sd
where sd.said in ('ClicPlan - España','ClicPlan - Francia','ClicPlan - UK',
                  'ClicPlan - Belgique','ClicPlan - Argentina',
                  'Clicplan - Turkey');

aid
----
3045
3253
3254
3260
3268
3270

In the code above Test-I, select from table said_aid doesn't return records, but should be 6 records output. Int the Test-II same query with hard coded IN values return 6 records output. No ERRORS during execution.

You have to use FIND_IN_SET() , because the IN clause expects literal values, so it won't work with the values inside a string variable, so replace your following line:

where sd.said in (@group_saids);

for this one:

where FIND_IN_SET(sd.said, @group_saids);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM