Mysql全文布尔搜索 - 按相关性和另一个字段排序

时间:2013-05-29 11:19:25

标签: mysql

所以基本上我有两张桌子。第一张名为“照片”的表格如下:

id title
1  Some text here
2  Another text here

第二个名为'likes'的表看起来像这样

id photos_id user_id
1  1         10
2  1         11
3  2         12

photos_id对应于“照片”表中的ID

我使用以下查询进行全文布尔搜索,然后按相关性排序

SELECT *, MATCH (title) AGAINST ('text' in boolean mode)
AS score FROM photos
WHERE MATCH (title) AGAINST ('text' in boolean mode) order by score desc;

按相关性进行排序效果很好,但现在我想在相关性相等时按照喜欢的总数进行排序......例如“按分数排序,total_likes desc ”。有什么帮助吗?

1 个答案:

答案 0 :(得分:3)

您可以Left Join为此,并在此处查看SQLFiddle

SELECT
  p.*,
       MATCH (title) AGAINST ('text' IN BOOLEAN MODE) AS score ,
       COUNT(li.id) AS total_likes 
FROM photos p
  LEFT JOIN likes li
    ON p.id = li.photo_id
     WHERE  MATCH (p.title) AGAINST ('text' IN BOOLEAN MODE) 
    GROUP BY 
      li.photo_id

ORDER BY 
      score , total_likes DESC