是否可以订购(DESC) MYSQL查询的结果,具体取决于 WHERE子句中的匹配数,已由多个OR运算符分隔?
我想对以下查询执行此操作:
SELECT column_1, column_2, column_2
FROM tbl_table
WHERE column_1 LIKE '%$string1%'
OR column_2 LIKE '%$string2%'
OR column_3 LIKE '%$string3%'
ORDER BY ... "
答案 0 :(得分:3)
您可以使用SUM()和GROUP BY:
SELECT column_1, column_2, column_3, SUM(IF(column_1 LIKE '%$string1%', 1, 0)) as S1, SUM(IF(column_2 LIKE '%$string2%', 1, 0)) as S2, SUM(IF(column_3 LIKE '%$string3%', 1, 0)) as S3 FROM tbl_table WHERE column_1 LIKE '%$string1%' OR column_2 LIKE '%$string2%' OR column_3 LIKE '%$string3%' GROUP BY column_1, column_2, column_3 ORDER BY S1 DESC, S2 DESC, S3 DESC
答案 1 :(得分:2)
这是我所知道的唯一方式:
SELECT column_1, column_2, column_2
, IF(column_1 LIKE '%$string1%', 1, 0)
+ IF(column_2 LIKE '%$string2%', 1, 0)
+ IF(column_3 LIKE '%$string3%', 1, 0)
AS matchCount
FROM tbl_table
WHERE column_1 LIKE '%$string1%'
OR column_2 LIKE '%$string2%'
OR column_3 LIKE '%$string3%'
ORDER BY matchCount DESC