tags:

views:

53

answers:

4
Table A Column aa
-----
jack
jim
alan

Table B Column bb
-----
jacky
jimmy
william

output is:
-----
jack jacky
jim jimmy

because aa's value is bb's substring. How to write this SQL?

A: 

You can try something like

DECLARE @TableA TABLE(
        AA VARCHAR(20)
)
INSERT INTO @TableA SELECT 'jack'
INSERT INTO @TableA SELECT 'jim'
INSERT INTO @TableA SELECT 'alan' 

DECLARE @TableB TABLE(
        BB VARCHAR(20)
)
INSERT INTO @TableB SELECT 'jacky'
INSERT INTO @TableB SELECT 'jimmy'
INSERT INTO @TableB SELECT 'william'

SELECT  *
FROM    @TableA A,
        @TableB B
WHERE   B.BB LIKE '%' + A.AA + '%'
astander
+2  A: 
Select aa, bb
from a, b
where a.aa like '%' + b.bb + '%'
   OR b.bb like '%' + a.aa + '%'

for mysql you need use concat('%', field, '%')

for oracle you need use '||' insteaf of '+'

Michael Pakhantsov
+2  A: 

You can construct a pattern from the substring:

select a.aa, b.bb
from TableA a
inner join TableB b on b.bb like '%' + a.aa + '%'
Guffa
A: 

You can do something like this:

SELECT
       a.aa, b.bb
FROM   
       a
JOIN   
       b ON b.bb like '%' + a.aa + '%'

But you have to be very carefully because you can find multiple rows returned for the same name.

Parkyprg