Thursday, 26 November 2009

SQL: select where like a subquery select

the syntax for select where like is

SELECT * FROM tablea
 WHERE column1 LIKE '%string%';


but it is not so simple for a subquery, and the following will not work,

SELECT * FROM tablea
 WHERE column1 LIKE '%select * from tableb%';

SELECT * FROM tablea
 WHERE column1 LIKE '%(select * from tableb)%';


the correct one is, it is the '%' and ||

select tb1.tb1data1, tb2.tb2data1 from tb1, tb2

 where tb1.tb1data1 like '%'||tb2.tb2data1'||%';

sqlite> select tb1data1 from tb1;
tb1data1
12236611890664780gNeqkz
12236613870664780koLReY
12236615610664780NrsBCn
12236617280664780ebOndn
12236619700664780RRnlXO
12236621890664780NyeBWy
12236623850664780qLIsUk
12236625610664780hfcgMe
12236627490664780UEWsIg
12236629400664780iVDYcs
sqlite> select tb1data1 from tb2;
tb2data1
223662189
223662385
sqlite> select tb1.tb1data1, tb2.tb2data1 from tb1, tb2 where tb1.tb1data1 like
'%'||tb2.tb2data1||'%';
tb1data1|tb2data1
1223662189060664780NyeBWy|223662189
1223662385060664780qLIsUk|223662385



to return only 1 column,

select tb1data1 from 
(
  select tb1.tb1data1, tb2.tb2data1 from tb1, tb2 
    where 
    tb1.tb1data1 like '%'||tb2.tb2data1||'%'
);

No comments:

Labels

Search This Blog