mysql:查询通过自定义搜索查找匹配的朋友

时间:2016-02-09 23:10:11

标签: php jquery mysql mysqli

我希望通过示例找到匹配的朋友(城市|年龄|性别|等)

用户选择从表单和html选择

中查找朋友

年龄(22至36岁之间) 性别女 ) 城市(a,b,c)

我的桌子像

---------------------------------------------
  member_id   |   member_key  | member_value    
---------------------------------------------
   2          |     city      |  a
---------------------------------------------
   2          |     gender    |  female
---------------------------------------------
   2          |     age       |  20
---------------------------------------------
   2          |     degree    |  5
---------------------------------------------
   3          |     city      |  x
---------------------------------------------
   3          |     gender    |  male
---------------------------------------------
   3          |     age       |  25
---------------------------------------------
   3          |     degree    |  3
---------------------------------------------
   4          |     city      |  a
---------------------------------------------
   4          |     gender    |  female
---------------------------------------------
   4          |     age       |  26
---------------------------------------------
   4          |     degree    |  3
---------------------------------------------

,我希望结果像这样

----------------------
member_id      |  match_count 
----------------------
4            |   3
----------------------
2            |   2
----------------------
3            |   1

我尝试了这样的查询,但没有工作

SELECT `member_id`, `member_key`, SUM(
    CASE `member_key`
        WHEN ( "age" AND `member_value` BETWEEN 22 AND 36 )
        THEN 1
        WHEN ( "city" and `member_value` IN ("a","b","c") )
        THEN 1
        WHEN ( "gender" and `member_value` = "male" )
        THEN 1
        ELSE 0
    END ) AS match_count
FROM members_info

我找到了这个解决方案,它看起来不错,但性能:(

SELECT member_id,concat_ws(",",member_key) as match_in,count(member_id) as match_count
FROM members_info WHERE
  ( member_key = "age" AND member_value BETWEEN 22 AND 36) OR 
  ( member_key = "city" AND member_value IN ('a', 'b', 'c') ) OR
  ( member_key = "gender" AND member_value = "female" )
GROUP BY member_id

1 个答案:

答案 0 :(得分:0)

现在我已经明白了你想要完成的事情。 这是另一种可能更快的方式。我希望它顺利运行:)

SELECT T.member_id, COUNT(*) AS affinity
FROM
    (SELECT member_id
    FROM members_info
    WHERE member_key = 'age' AND member_value BETWEEN 22 AND 36
    UNION
    SELECT member_id
    FROM members_info
    WHERE member_key = 'city' AND member_value IN ('a', 'b', 'c')
    UNION
    SELECT member_id
    FROM members_info
    WHERE member_key = 'gender' AND member_value = 'female') AS T
GROUP BY T.member_id