I have a following table structure.
USERS
PROPERTY_VALUE
PROPERTY_NAME
USER_PROPERTY_MAP
I am trying to retrieve user/s from the users
table who have matching properties in property_value
table.
A single user can have multiple properties. The example data here has 2 properties for user '1', but there can be more than 2. I want to use all those user properties in the WHERE
clause.
This query works if user has a single property but it fails for more than 1 properties:
SELECT * FROM users u
INNER JOIN user_property_map upm ON u.id = upm.user_id
INNER JOIN property_value pv ON upm.property_value_id = pv.id
INNER JOIN property_name pn ON pv.property_name_id = pn.id
WHERE (pn.id = 1 AND pv.id IN (SELECT id FROM property_value WHERE value like '101')
AND pn.id = 2 AND pv.id IN (SELECT id FROM property_value WHERE value like '102')) and u.user_name = 'user1' and u.city = 'city1'
I understand since the query has pn.id = 1 AND pn.id = 2
it will always fail because pn.id
can be either 1 or 2 but not both at the same time. So how can I re-write it to make it work for n number of properties?
In above example data there is only one user with id = 1
that has both matching properties used in the WHERE
clause. The query should return a single record with all columns of the USERS
table.
To clarify my requirements
I am working on an application that has a users list page on the UI listing all users in the system. This list has information like user id, user name, city etc. - all columns of the in USERS
table. Users can have properties as detailed in the database model above.
The users list page also provides functionality to search users based on these properties. When searching for users with 2 properties, 'property1' and 'property2', the page should fetch and display only matching rows. Based on the test data above, only user '1' fits the bill.
A user with 4 properties including 'property1' and 'property2' qualifies. But a user with only one property 'property1' would be excluded due to the missing 'property2'.
OR
,group by
andhaving count(*)=2
– InfiltrateCREATE TABLE
statements). – Mariquilla