简体   繁体   English

SQL查询用于获取同一行的列中提到的具有其ID的行

[英]SQL query for fetching rows with their id mentioned in a column of that same row

I am trying to get those rows whose Id's I have described in a column of that same table . 我试图获得那些ID在同一张表的一栏中描述的行。 Here's the data: 数据如下:

id    layer    sublayer
1     A        2, 3, 4
2     B        5
3     C        NULL
4     D        NULL
5     E        NULL

Here's what I am trying to do. 这就是我想要做的。 For layer A ,I want to fetch B,C,D whose id's are described in the column sublayer . 对于A层,我想获取B,C,D,其ID在列子层中描述。 Here id is the primary key.Is it possible to read individual values from a column separated with special characters ? id是主键,是否可以从以特殊字符分隔的列中读取单个值?

Using Find_In_set function for set datatypes in conjunction with group_concat (cross join may not be needed but I like it for the fact it calculates the set once instead of for each row..) find_In_set函数与group_concat结合使用以设置数据类型(可能不需要交叉连接,但我喜欢它,因为它只计算一次集合,而不是每行计算一次。)

I'm using group concat to bring all the rows into one large data set so we can simply check for the existence of the ID. 我正在使用concat组将所有行放入一个大数据集中,因此我们可以简单地检查ID的存在。 However, I'm not sure how well group_concat will work with a set datatype already having a , separated values... 但是,我不确定group_concat对已具有,分隔值的集合数据类型的工作情况如何...

On a large data set I would be concerned about performance. 对于大数据集,我会担心性能。 Your best bet long term is to normalize the data. 长期以来,最好的选择是对数据进行标准化。 But if that's not an option... 但是如果那不是一个选择...

Working SQL Fiddle: 有效的SQL提琴:

SELECT * 
FROM layer
CROSS JOIN (SELECT group_Concat(sublayer separator ',') v FROM layer) myset
WHERE FIND_IN_SET(ID, myset.v) > 0;

try this way 尝试这种方式

SELECT * 
FROM layer
WHERE FIND_IN_SET(ID,(
      select sublayer from table where layer='A'))>1

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

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