mysql 按相似性來排序

來源:互聯網
上載者:User
資料庫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)


----------------插入資料```sqlmysql> 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

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.