Using same column multiple times in WHERE clause

前端 未结 8 740
醉话见心
醉话见心 2020-12-15 10:19

I have a following table structure.

USERS

PROPERTY_VALUE

PROPERTY_NAME

USER_

相关标签:
8条回答
  • 2020-12-15 10:54

    If you just want the distinct columns in U, it is:

    SELECT DISTINCT u.* 
      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.[value] = '101')
         OR (pn.id = 2 AND pv.[value] = '102')
    

    Notice I used pv.[value] = instead of the subquery to reacquire id... this is simplification.

    0 讨论(0)
  • 2020-12-15 10:56

    If you want just to filter:

    SELECT users.*
    FROM users
    where (
        select count(*)
        from user_property_map
        left join property_value on user_property_map.property_value_id = property_value.id
        left join property_name on property_value.property_name_id = property_name.id
        where user_property_map.user_id = users.id -- join with users table
        and (property_name.name, property_value.value) in (
            values ('property1', '101'), ('property2', '102') -- filter properties by name and value
        )
    ) = 2 -- number of properties you filter by
    

    Or, if you need users ordered descending by number of matches, you could do:

    select * from (
        SELECT users.*, (
            select count(*) as property_matches
            from user_property_map
            left join property_value on user_property_map.property_value_id = property_value.id
            left join property_name on property_value.property_name_id = property_name.id
            where user_property_map.user_id = users.id -- join with users table
            and (property_name.name, property_value.value) in (
                values ('property1', '101'), ('property2', '102') -- filter properties by name and value
            )
        )
        FROM users
    ) t
    order by property_matches desc
    
    0 讨论(0)
提交回复
热议问题