简体   繁体   English

如何在mySQL级联SELECT语句中使用'IN'语句?

[英]How to use 'IN' statement in mySQL cascaded SELECT statement?

I have two tables A and B. I need to pull data from them in a combined statement using GROUP_CONCAT.我有两个表 A 和 B。我需要使用 GROUP_CONCAT 在组合语句中从它们中提取数据。 Currently, it does not work as I expected.目前,它不像我预期的那样工作。 So I separated the statement into two seperated simple statements to test.所以我把语句分成两个单独的简单语句来测试。

This is how I did.我就是这样做的。

Tabel A
FIELD1 FIELD
1      A  
2      B
3      C

Table B
FIELD1  FIELD2
1       1,2
2       1
3       2,3

I can read the Tabel B as follows我可以按如下方式阅读表 B

SELECT B.FIELD2 FROM B WHERE FIELD1=3

Output is输出是

FIELD2
2,3

Now if I read Tabel A as follows现在,如果我按如下方式阅读表 A

SELECT GROUP_CONCAT(A.FIELD2) FROM A WHERE FIELD1 IN (2,3)

I get我得到

FIELD2
B,C

Now I want to get the same output with the following statement but it fails.现在我想使用以下语句获得相同的输出,但它失败了。

SELECT GROUP_CONCAT(A.FIELD2) FROM A WHERE FIELD1 IN (SELECT B.FIELD2 FROM B WHERE FIELD1=3)

Any help fixing the statement?任何帮助修复声明?

This is slightly difficult to explain.这有点难以解释。 The IN operator doesn't look at a CSV string in a column and treat it like a comma separated list of values to be looked through. IN 运算符不会查看列中的 CSV 字符串,而是将其视为要查看的逗号分隔值列表。 If a column value is some CSV data then the in operator will look for that exact string, commas and everything, in some other list of values如果列值是一些 CSV 数据,则 in 运算符将在其他一些值列表中查找确切的字符串、逗号和所有内容

2 IN (1,2) --true
'2' IN ('1','2') --true
'2' IN ('1,2') --false 
'1,2' IN ('1,2') --true

Always remember that your SQL is compiled like any other program.永远记住,您的 SQL 是像任何其他程序一样编译的。 Data that you write into the statement becomes part of the program.您写入语句的数据成为程序的一部分。 Data in the table does NOT become part of the program.表中的数据不会成为程序的一部分。 This is why you can't use IN on some comma separated list of stuff you find in a table row这就是为什么您不能在表格行中找到的一些以逗号分隔的内容列表上使用 IN

As it stands you'll have to split the '2,3' to two rows of '2' and '3', or keep it as a string and use like就目前而言,您必须将“2,3”拆分为两行“2”和“3”,或者将其保留为字符串并使用类似

SELECT GROUP_CONCAT(A.FIELD2) 
FROM A
  INNER JOIN B 
  ON CONCAT(',', B.FIELD2, ',') LIKE CONCAT('%,', A.FIELD1, ',%')
WHERE B.FIELD1=3

Nasty!可恶的! :) :)

You can'd do it with the IN operator because B.FIELD2 is not a list of values (which is what IN expects) but a string.您可以使用IN运算符来完成它,因为B.FIELD2不是值列表(这是IN期望的)而是一个字符串。
You must join the tables and use FIND_IN_SET() :您必须加入表并使用FIND_IN_SET()

SELECT GROUP_CONCAT(A.FIELD2) FIELD2
FROM A INNER JOIN B
ON FIND_IN_SET(A.FIELD1, B.FIELD2)
WHERE B.FIELD1 = 3;

See the demo .请参阅演示
Results:结果:

| FIELD2 |
| ------ |
| B,C    |

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

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