MySQL请求按常用值排序

时间:2015-01-24 15:22:01

标签: php mysql

我面临一个小的SQL查询问题。

让我解释一下我会做什么。

我有一个会员表,我会按两个成员之间共同的主题标签数排序。

这是为约会网站创建建议列表。

在我的第一个表“成员”中,我使用“idmem。”

在第二个“hashtags”中,我有以下列:“idhash”,“idmem”,“hashtags。”

目前我正在提出此请求。

SELECT m.*, 
       nbhash.nb
  FROM member AS m
             INNER JOIN
               (SELECT count(*) AS nb, 
                       mh.idmem 
                  FROM hashtags AS h 
                           INNER JOIN hashtags AS mh 
                              ON h.hashtags = mh.hashtags 
                 WHERE h.idmem = '3016') nbhash
 WHERE m.idmem != '3016'
   AND m.sexe = 'female'
   AND m.orientsexe = 'male'
   AND nbhash.idmem = m.idmem 

member table

idmem | pseudo   | sexe   | orientsexe |
3016  | jhon     | male   | female     |
3017  | laura    | female | male       |
3018  | david    | male   | male       |
3019  | jessica  | female | male       |
3020  | clara    | female | female     |
3021  | isabelle | female | male       |
3022  | melanie  | female | male       |
3023  | fred     | male   | female     |

hashtags table

idhash | idmem | hashtags
1      | 3016  | basketball
2      | 3016  | cinema
3      | 3017  | basketball
4      | 3017  | cinema
5      | 3019  | basketball
6      | 3020  | cinema
7      | 3021  | basketball
8      | 3021  | football

我希望按此顺序查看:

Laura(3017),Isabelle(3021),Jessica(3019),Melanie(3022)

因为Laura和Jhon(我)有2个相同的标签,isabelle和我有1个相同的标签...... 即使她没有任何标签,我也希望看到Melanie!

1 个答案:

答案 0 :(得分:1)

我认为您必须需要order byleft join

SELECT m.*,  coalesce(nbhash.nb, 0)
FROM member m LEFT JOIN
     (SELECT count(*) AS nb,  mh.idmem 
      FROM hashtags h INNER JOIN
           hashtags mh 
           ON h.hashtags = mh.hashtags 
      WHERE h.idmem = '3016'
     ) nbhash
     ON nbhash.idmem = m.idmem 
WHERE m.idmem <> '3016' AND m.sexe = 'female' AND m.orientsexe = 'male'
ORDER BY coalesce(nbhash.nb, 0) DESC