当前位置:Gxlcms > PHP教程 > mysql按相似度来排序

mysql按相似度来排序

时间:2021-07-01 10:21:17 帮助过:9人阅读

数据库tag字段内容格式:a,b,c,d ...
假设有这几条记录
1:刘世允
2:郑胜浩
3:申东烨
4: 申东烨,郑胜浩,刘世允,安英美
5: 郑胜浩,刘世允,安英美
6: 申东烨,郑胜浩
7:刘世允,安英美

给出的查询tag
$tag = '申东烨,郑胜浩,刘世允,安英美,李尚勋';
按照相同词的个数排序

查询的结果
1: 申东烨,郑胜浩,刘世允,安英美
2: 郑胜浩,刘世允,安英美
3: 申东烨,郑胜浩
4:刘世允,安英美
5:刘世允
6:郑胜浩
7:申东烨

回复内容:

数据库tag字段内容格式:a,b,c,d ...
假设有这几条记录
1:刘世允
2:郑胜浩
3:申东烨
4: 申东烨,郑胜浩,刘世允,安英美
5: 郑胜浩,刘世允,安英美
6: 申东烨,郑胜浩
7:刘世允,安英美

给出的查询tag
$tag = '申东烨,郑胜浩,刘世允,安英美,李尚勋';
按照相同词的个数排序

查询的结果
1: 申东烨,郑胜浩,刘世允,安英美
2: 郑胜浩,刘世允,安英美
3: 申东烨,郑胜浩
4:刘世允,安英美
5:刘世允
6:郑胜浩
7:申东烨

----------------建表

mysql> create table testsort (tag varchar(100) charset "GBK");
Query OK, 0 rows affected (0.51 sec)

```sql
mysql> describe testsort
-> ;
+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| tag | varchar(100) | YES | | NULL | |
+-------+--------------+------+-----+---------+-------+
1 row in set (0.07 sec)


----------------插入数据 ```sql mysql> insert into testsort(id,tag) values(1,"刘世允"), -> (2,"郑胜浩"), -> (3,"申东烨"), -> (4,"申东烨,郑胜浩,刘世允,安英美"), -> (5,"郑胜浩,刘世允,安英美"), -> (6,"申东烨,郑胜浩"), -> (7,"刘世允,安英美"); Query OK, 7 rows affected (0.07 sec) Records: 7 Duplicates: 0 Warnings: 0

----------------方法

mysql> select id,
    -> tag,
    -> char_length(tag)-char_length(replace(tag,',',''))+1 as cnt
    -> from testsort;
+------+-----------------------------------------+------+
| id   | tag                                     | cnt  |
+------+-----------------------------------------+------+
|    1 | 刘世允                                  |    1 |
|    2 | 郑胜浩                                  |    1 |
|    3 | 申东烨                                  |    1 |
|    4 | 申东烨,郑胜浩,刘世允,安英美             |    4 |
|    5 | 郑胜浩,刘世允,安英美                    |    3 |
|    6 | 申东烨,郑胜浩                           |    2 |
|    7 | 刘世允,安英美                           |    2 |
+------+-----------------------------------------+------+
7 rows in set (0.00 sec)

----------------另外注意
Responses below will get you there. However, don't forget to use CHAR_LENGTH() instead of LENGTH() if you're using multibyte characters. – inhan Sep 10 '12 at 3:03

http://stackoverflow.com/questions/12344795/count-the-number-of-occurences-of-a-string-in-a-varchar-field

人气教程排行