DB column extract and split to find other table result

拈花ヽ惹草 提交于 2019-12-10 23:21:20

问题


I have table1 where Temp_ID column is combination of ID column values form table2 and table3.

Example: table1_id:table2_id {values like (1:1,2:2)}

What I do in my Java code I need to use Temp_ID and split according to COLON(:), and then we can get table 2 and table 3 data using ID values obtained from split.

But table1 can have huge data, so if i do this in java I need to run 2 queries again and again.

Is it possible to write query, So i can do this split of Temp_ID in query and use those to do JOIN and get data in MS SQL itself.


回答1:


Neat thinking I'd say. Here's a query for doing something like that

SELECT 
t1.temp_id
   --  ... put your column list here from t2 and t3 here like t2.name
FROM table1 t1 
  LEFT JOIN table2 t2 
     ON CAST(LEFT(t1.temp_id,CHARINDEX(':',t1.temp_id)-1) AS INT)=t2.ID
  LEFT JOIN table3 t3 
     ON CAST(RIGHT(t1.temp_id,CHARINDEX(':',REVERSE(t1.temp_id))-1) AS INT)=t3.ID

Here's a small script for testing this out as well

create table table1 (temp_id varchar(10))
insert into table1 values('1:1'),('21:2'),('1:22'),('1:'),(':2')

create table table2 (id int, value varchar(2))
insert into table2 values (1,'1'),(21,'21'),(1,'1')

create table table3 (id int, value varchar(2))
insert into table3 values (1,'1'),(2,'2'),(22,'22')

Output PS: Note the null handling in the output



来源:https://stackoverflow.com/questions/35954390/db-column-extract-and-split-to-find-other-table-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!