简体   繁体   中英

Existence of a string in one row/recordusing a different column and row of the same table?

Trying to determine how to return a T/F if a specific id (set as a string) exists in another column and row that contains a string as well. Data looks like this:

key1 key2 string
0001 0001 null
0002 0002 null
0003 0003 0001;0002

I don't know (and neither do the producers) of the data know how many; to parse the string.

I've run out of system resources trying to use regexp_contains as well as joining (trying to limit the string down to nonull records and then joining). I've tried using IN and EXISTS and since it's a different row that the one being evaluated, and I suspect that doesn't work because the string value is a strict evaluation unlike LIKE.

Here are some sample solutions that are not working (these don't include the T/F, just trying to join the data):

WITH limit_data AS (
  SELECT string FROM my table
  WHERE string IS NOT NULL),


merged_filtering AS (
SELECT key1,
CASE WHEN key1 IN (SELECT string FROM limit_data) THEN TRUE ELSE FALSE END AS merged
FROM table1)

SELECT * FROM merged_filtering WHERE merged IS TRUE

or

WITH limit_data AS (
  SELECT string FROM table1
  WHERE string IS NOT NULL)

SELECT key1
FROM table1 AS p
LEFT JOIN limit_data ON regexp_contains(limit_data.string, p.key1)

Neither works because the IN/EXISTS isn't evaluating like I need it to, and joining with regexp_contains consumes more than 10k CPU, 2.5K limit.

You can try this

declare @tbl TABLE(Column1 VARCHAR(15),Column2 VARCHAR(15),Column3 
VARCHAR(150));
INSERT INTO @tbl VALUES
('ABC','123','User7;User9')  
,('nbm','qre','User1;User2;User3')  
,('POI','kjh','User1;User4;User5;User9');

WITH Splitted AS
 (
 SELECT Column1,Column2,CAST('<x>'+REPLACE(Column3,';','</x><x>')+'</x>' AS XML) 
 AS Col3Splitted
 FROM @tbl
 ) 
  SELECT Column1,Column2,Col3Splitted
                  ,Col3Splitted.value('x[1]','varchar(max)') AS Column4
                  ,Col3Splitted.value('x[2]','varchar(max)') AS Column5
                  ,Col3Splitted.value('x[3]','varchar(max)') AS Column6
                  ,Col3Splitted.value('x[4]','varchar(max)') AS Column7
                
 FROM Splitted

 

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