简体   繁体   中英

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 . 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 . Here id is the primary key.Is it possible to read individual values from a column separated with special characters ?

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..)

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. However, I'm not sure how well group_concat will work with a set datatype already having a , separated values...

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:

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

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