Normalize your schemas so there's a separate row for each row.
House_roles
House_name Role
r_house_1 1
r_house_1 2
r_house_1 3
r_house_2 2
r_house_2 3
r_house_3 1
r_house_3 3
r_house_4 1
r_house_4 2
User_roles
User_name Role
Manu 1
John 1
John 2
Sunny 3
Jack 1
Jack 2
Then the query is a join between these two tables:
SELECT House_name
FROM House_roles AS h
JOIN User_roles AS u ON h.role = u.role
WHERE u.User_name = 'Manu'
If you can't change the schema, see SQL split values to multiple rows for how to write a query to split the comma-delimited lists into rows. If a house or user can have up to 100 roles, create a table numbers
that contains the numbers from 1 to 100 in a column named n
. Then you can create temporary tables like this by joining your tables with the numbers
table. Here's the query to create House_roles
:
CREATE TEMPORARY TABLE House_roles (
House_name VARCHAR(32),
Role INT,
INDEX(Role)
) AS
SELECT h.name, SUBSTRING_INDEX(SUBSTRING_INDEX(h.role, ',', n.n), ',', -1)
FROM House AS h
JOIN numbers AS n ON CHAR_LENGTH(h.role)
-CHAR_LENGTH(REPLACE(h.role, ',', ''))>=n.n-1
It's similar for User_roles
.