Rafiqul Islam
Rafiqul Islam

Reputation: 225

MySQL find if one column contains any values of another column

ID business_name district
1 dhaka bank cumilla
2 cumilla dodhi rajshahi
3 maloncha dhaka
4 dhaka bank dhaka

I need the query to find the business name that contains any district

ID business_name district
1 dhaka bank cumilla
2 cumilla dodhi rajshahi
4 dhaka bank dhaka

Your help is greatly appreciated. Thank You.

Upvotes: 1

Views: 491

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522762

Use exists logic along with word boundaries:

SELECT ID, business_name, district
FROM yourTable t1
WHERE EXISTS (
    SELECT 1
    FROM yourTable t2
    WHERE t1.business_name REGEXP CONCAT('\\b', t2.district, '\\b')
    -- Note: On MySQL 5.7 and earlier use:
    -- WHERE t1.business_name REGEXP CONCAT('[[:<:]]', t2.district, '[[:>:]]')
);

Upvotes: 3

Related Questions