我正在尝试根据匹配的列数来排序搜索结果。
变量: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
答案 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;
编辑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;