简体   繁体   中英

MySQL SELECT * FROM table WHERE id IN (subquery)

I have a field that contains a string like so:

["688024","688023","688025"]

Each of these values relates to an ID in another table. I can strip the brackets and quotes like so:

SELECT REPLACE(REPLACE(REPLACE(myField,'"',""),'[',''),']','') FROM myTable WHERE myID = 123456

This gives me:

688024,688023,688025

I then want to use this in an IN statement like so:

SELECT * FROM myOtherTable WHERE myOtherID IN (SELECT REPLACE(REPLACE(REPLACE(myField,'"',""),'[',''),']','') FROM myTable WHERE myID = 123456)

However, it only returns 1 result, which is ID 688024 (the first one). If I do the following I get 3 results:

SELECT * FROM myOtherTable WHERE myOtherID IN (688024,688023,688025)

Why would the subquery only give me 1 result? Thanks.

You may use FIND_IN_SET :

SELECT *
FROM myOtherTable t1
WHERE EXISTS (SELECT 1 FROM myTable t2
              WHERE myID = 123456 AND
              FIND_IN_SET(t1.myOtherID,
                  REPLACE(REPLACE(REPLACE(myField, '"', ""), '[', ''), ']', '')) > 0);

But note that your current table design is suboptimal, because you are storing CSV data. A better approach for the myTable table would be to have each myField value on a separate row, something like this:

myID   | myField
123456 | 688024
123456 | 688023
123456 | 688025

Then, you would only need a much simpler query:

SELECT *
FROM myOtherTable t1
WHERE EXISTS (SELECT 1 FROM myTable t2
              WHERE myID = 123456 AND t1.myOtherID = t2.myField);

Are you sure WHERE myID = 123456 isn't conflicting with what you want to achieve? As I look at it, it's causing the problem, it only returns the record with such id.

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