简体   繁体   English

MySQL SELECT * FROM表WHERE ID IN(子查询)

[英]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. 这些值中的每一个都与另一个表中的ID相关。 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: 然后,我想像这样在IN语句中使用它:

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). 但是,它仅返回1个结果,即ID 688024(第一个)。 If I do the following I get 3 results: 如果执行以下操作,我将得到3个结果:

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

Why would the subquery only give me 1 result? 为什么子查询只会给我1个结果? Thanks. 谢谢。

You may use FIND_IN_SET : 您可以使用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. 但是请注意,由于您存储的是CSV数据,因此当前的表格设计不是最佳的。 A better approach for the myTable table would be to have each myField value on a separate row, something like this: myTable表的一种更好的方法是将每个myField值放在单独的行上,如下所示:

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? 您确定WHERE myID = 123456与要实现的目标不冲突吗? As I look at it, it's causing the problem, it only returns the record with such id. 在我看来,这是导致问题的原因,它仅返回具有此类ID的记录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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