SQL: Join tables on substrings

2019-04-28 13:23发布

问题:

I have a table A with the string-column a and a table B with the string-column b. a is a substring of b. Now I want to join the the two tables on a and b. Is this possible?

I want something like this:

Select * from A,B where A.a *"is substring of"* B.b

How can I write this in SQL (Transact-SQL)?

回答1:

You can use like

select *
from A
  inner join B 
    on B.b like '%'+A.a+'%'


回答2:

declare @tmp1 table (id int, a varchar(max))
declare @tmp2 table (id int, b varchar(max))


insert into @tmp1 (id, a) values (1,'one')
insert into @tmp2 (id,b) values (1,'onetwo')

select * from @tmp1 one inner join @tmp2 two on charindex(one.a,two.b) > 0

You can also use charindex, 0 means its not found, greater than 0 is the start index

charindex



回答3:

set an inner join on a substring(4 letters) of FIELD1 of table TABLE1 with FIELD1 of table TABLE2

select TABLE1.field1,TABLE2.field1 from TABLE1 inner join TABLE2 on substring(TABLE1.field1,2,5)=TABLE2.field1


回答4:

You have the contains function: http://msdn.microsoft.com/en-us/library/ms187787.aspx

select * from A,B where contains(B.b, A.a)


回答5:

try this:

Select * from A,B where B.b LIKE '%'+A.a+'%'