简体   繁体   中英

MySQL: Using a string in a "WHERE <column_name> IN <values>" Query

Dear Stackoverflow members,

I hope that I'm not overlooking something obvious, but I haven't been able to find a solution to my problem so far.

I need to obtain certain column values from a table, using a standard WHERE... IN ( 1, 2, 3, 4 ) clause. The problem, however, is that the values in the WHERE clause have to be built dynamically, based on values stored in columns of another table, that look something like 'a:3:{i:0;s:3:"153";i:1;s:3:"211";i:2;s:3:"226";}' . The values to be extracted are, in this example, 153, 211, and 226 resulting in the clause WHERE <column> IN ( 153, 211, 226 ) . The formatting of this string is always the same, but the number of values can vary.

I can obtain the actual values from this string, using some RegExp trickery with

SELECT value from `column` WHERE <non-scary WHERE clause> INTO @valueString;
SET @IDs =  CONVERT(PREG_REPLACE('/[^\"]+\"([^\"]+)\".*/', '$1', PREG_REPLACE( '/\"\;[^\"]+\"/', '\,\ ', @valueString  )) USING UTF8);

The function PREG_REPLACE is a UDF, from [http://www.mysqludf.org/lib_mysqludf_preg/], which is the one generally recommended, whenever people are looking for RegExp/Replace functions. The CONVERT() is there, because the PREG_REPLACE gives me back a blob, instead of a readable string.

After running these queries, running

SELECT @IDs;

gives me a list of values, looking like (in this example) 153, 211, 226 .

The question is now, how I can convince MySQL to use these values in the WHERE... IN clause. The naive query

SELECT * FROM `table` WHERE id IN  ( SELECT @IDs );   

does not complain as such, but only gives back the result for the first of the values in the list, ignoring the other ones (I have to admit, that I don't really understand why it does that).

Quite obviously, this would all be trivial to do in eg, Ruby, Python, Perl, etc. but for technical reasons, it has to be done strictly in SQL. One of the suggestions a colleague gave me, is to use a temporary table, to write the intermediate results, but I'm not sure if I see how that'd be implemented and/or work. Moreover, I don't think it can be done easily without lots of loops, substring stuff and other ugliness, but I stand to be corrected.

I hope the description of my problem is more or less clear. I'd appreciate any insights, ideas and hints.

Thanks in advance for your time and mindshare, Constantijn Blondel, Leipzig DE

Select a sub query in your where clause it will work ok.

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