Mysql字串欄位中是否包含某個字串,用 find_in_set

來源:互聯網
上載者:User

標籤:http   ar   sp   strong   on   資料   div   問題   bs   

有這樣一個需求,在Mysql資料庫字串欄位(許可權)中,有範圍在 1 到 N 之間代表不同許可權的值,分別被‘,’分開,現在要取出具有某許可權的所有成員列表。

建立表:

 
1 CREATE TABLE users(id int(6) NOT NULL AUTO_INCREMENT,PRIMARY KEY (id),name VARCHAR(20) NOT NULL,limits VARCHAR(50) NOT NULL);

添加資料:

1 INSERT INTO users(name, limits) VALUES(‘小張‘,‘1,2,12‘);
2 INSERT INTO users(name, limits) VALUES(‘小王‘,‘11,22,32‘);

Mysql 中有些欄位是字串類型的,如何尋找其中包含某些字元的記錄呢?

方法一:

 
1 mysql> SELECT * FROM users WHERE limits like "%2%";
2 +----+----+--------+
3 | id |name| limits |
4 +----+----+--------+
5 |  1 |小張| 1,2,12 |
6 +----+----+--------+
7 |  2 |小王|11,22,32|
8 +----+----+--------+
9 2 row in set

這樣第二條資料不具有許可權‘2’的使用者也查出來了,不符合預期。所以就查閱了手冊,利用mysql 字串函數 find_in_set()。

方法二:

1 mysql> SELECT * FROM users WHERE find_in_set(‘2‘, limits);
2 +----+----+--------+
3 | id |name| limits |
4 +----+----+--------+
5 |  1 |小張| 1,2,12 |
6 +----+----+--------+
7 1 row in set

這樣就能達到我們預期的效果,問題就解決了!

注意:mysql字串函數 find_in_set(str1,str2)函數是返回str2中str1所在的位置索引,str2必須以","分割開。

Mysql字串欄位中是否包含某個字串,用 find_in_set

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.