简体   繁体   English

如何对 mysql 结果进行排序?

[英]How to sort an mysql Result?

Table:桌子:

 id        title

1.         php is a good language.
2.         Java is a good language
3.         All language are good
4.         Php,Java both good language
5.         Php is good but Java is not

Question问题

string: $#字符串:$#

$string = "php Java language"

Result Order结果顺序

php ,Java both  good language
-------------------------
php is good Java is not

-------------------------
php is good language 
---------------------------
Java is good language
------------------------
all language are good

I have no idea how to achive the order list by how many words are matched in string.我不知道如何通过字符串中匹配的单词数来获得订单列表。

It will be great if you explain the query.如果您解释查询,那就太好了。

Thank you.谢谢你。

Convert your string to JSON array then然后将您的字符串转换为 JSON 数组

SELECT test.id, test.tittle
FROM test
LEFT JOIN JSON_TABLE(@criteria, 
                     "$[*]" COLUMNS (word VARCHAR(255) PATH "$")) jsontable ON LOCATE (jsontable.word, test.tittle)
GROUP BY test.id, test.tittle
ORDER BY SUM(jsontable.word IS NOT NULL) DESC

@criteria is a placeholder for JSON array mentioned above. @criteria是上述 JSON 数组的占位符。

Of course, you may provide your criteria as space-separated string and convert it to JSON in the query using string functions.当然,您可以将您的条件提供为以空格分隔的字符串,并在使用字符串函数的查询中将其转换为 JSON。


The version without JSON usage:没有 JSON 用法的版本:

WITH RECURSIVE
cte AS (SELECT test.id, 
               test.tittle, 
               0 amount, 
               TRIM(TRIM(LEADING SUBSTRING_INDEX(@criteria, ' ', 1) FROM @criteria)) criteria, 
               SUBSTRING_INDEX(@criteria, ' ', 1) token
        FROM test
        UNION ALL
        SELECT id, 
               tittle,
               amount + (LOCATE(token, tittle) > 0),
               TRIM(TRIM(LEADING token FROM criteria)),
               SUBSTRING_INDEX(criteria, ' ', 1)
        FROM cte
        WHERE TRIM(criteria) != '' )
SELECT id, tittle
FROM cte
GROUP BY id, tittle
ORDER BY MAX(amount) DESC;

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=3ab611ed7429e23be2abfcb8b0186e6d https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=3ab611ed7429e23be2abfcb8b0186e6d

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM