Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to like two columns in one SQL statement

Tags:

How to write this SQL?

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

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

The output is:

-----
jack jacky
jim jimmy

Because aa's value is bb's substring.

like image 518
William_He Avatar asked Sep 30 '10 08:09

William_He


People also ask

How do I match two columns of data in SQL?

In SQL, problems require us to compare two columns for equality to achieve certain desired results. This can be achieved through the use of the =(equal to) operator between 2 columns names to be compared.

Can we use two like in SQL?

The LIKE command is used in a WHERE clause to search for a specified pattern in a column. You can use two wildcards with LIKE : % - Represents zero, one, or multiple characters. _ - Represents a single character (MS Access uses a question mark (?)

How do I show two columns in one column in SQL?

By replacing the existing column using REPLACE() function with CONCAT() function.

Can we sort 2 columns in SQL?

If you want to select records from a table but would like to see them sorted according to two columns, you can do so with ORDER BY . This clause comes at the end of your SQL query.


2 Answers

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 '+'

like image 94
Michael Pakhantsov Avatar answered Sep 21 '22 18:09

Michael Pakhantsov


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 + '%'
like image 36
Guffa Avatar answered Sep 17 '22 18:09

Guffa