使用GROUP_CONCAT时,如何按照匹配的字段数排序行?

时间:2016-03-27 15:42:17

标签: mysql

我正在尝试根据匹配的列数来排序搜索结果。

变量:Name:Email:Fullnumbers在PHP之前和之后获得%。

当我省略ORDER BY子句时,查询工作正常。当我从ORDER BY子句中删除Fullnumbers时,它也有效。 名称和电子邮件部分匹配的行将按正确的顺序返回。 但是,当包含Fullnumbers时,不会返回任何行。

为什么会这样,我该如何解决这个问题?

SELECT SQL_CALC_FOUND_ROWS DISTINCT(User.UserId), Name, Email,
GROUP_CONCAT(CONCAT(Countrycode, Number)) AS Fullnumbers
FROM User LEFT JOIN UserPhonenumber ON User.UserId = UserPhonenumber.UserId
GROUP BY UserId HAVING Name LIKE :Name OR Email LIKE :Email OR Fullnumbers LIKE :Fullnumbers
ORDER BY ((Name LIKE :Name) + (Email LIKE :Email) + (Fullnumbers LIKE :Fullnumbers)) DESC

1 个答案:

答案 0 :(得分:0)

然后,您想要使用ORDER BY CASE子句。这是一个例子:

ORDER BY CASE
  WHEN Name LIKE :Name THEN 1
  WHEN Email LIKE :Email THEN 2
  WHEN Fullnumbers LIKE :Fullnumbers THEN 3
  ELSE 4 END;

修改

使用多个IF子句,您可以按相关性排序结果集。

ORDER BY
  IF (Name LIKE :Name,1,0) + 
  IF (Email LIKE :Email,1,0) +
  IF (Fullnumbers LIKE :Fullnumbers,1,0) 
DESC;

参考:MySQL order by relevance

编辑2 解决方案:

SELECT * FROM (
  SELECT SQL_CALC_FOUND_ROWS DISTINCT(User.UserId), Name, Email,
  GROUP_CONCAT(CONCAT(Countrycode, Number)) AS Fullnumbers
  FROM User LEFT JOIN UserPhonenumber ON User.UserId = UserPhonenumber.UserId
  GROUP BY UserId HAVING Name LIKE :Name OR Email LIKE :Email OR Fullnumbers LIKE :Fullnumbers) AS t1
ORDER BY
  IF (Name LIKE :Name,1,0) + IF (Email LIKE :Email,1,0) + IF (Fullnumbers LIKE :Fullnumbers,1,0) DESC;