SQL語句中find_in_set、like、in的區別及使用方法
摘自 https://blog.csdn.net/sunny1660/article/details/78613000
find_in_set(str,strlist)函數
str 要查詢的字符串
strlist 字段名, 參數以“,”分割 如(1,2,3,4)
查詢字段(strlist)中包含(str)的結果,返回結果為null,或者記錄。
基本語法使用
1、in查詢相當於多個or條件的疊加。例如:
select * from user where user_id in (1,2,3);
等效於
select * from user where user_id = 1 or user_id = 2 or user_id = 3
not in 與 in相反
2、+---+--------+
| id | follow_id |
+----+-------+
| 1 | 14,15 |
| 2 | 13 |
這時,select * from test where find_in_set(‘5‘,follow_id);這樣是查不到的,返回值為null,因為follow_id中沒有“5”這個值,它不同於like模糊查詢,它是以“,”來分割。
如果使用like查詢,查詢結果為id=1的一條記錄。
sql中like用法,可以參考 :http://blog.sina.com.cn/s/blog_a74f39a201018jal.html
總結:
find_in_set與like的區別
like是廣泛的模糊匹配,字符串中沒有分隔符,find_in_set是精確匹配,字段值以英文“,”分隔,find_in_set查詢的結果要小於like查詢的結果。
find_in_set與in的區別
select * from table_name where ‘test‘ in (list);
select * from table_name where find_in_set(‘test‘,list);
res1 = Author.objects.raw(raw_query=‘SELECT id FROM book_author WHERE FIND_IN_SET(%s,name)‘,params=[‘11‘])
# <RawQuerySet: select * from book_author WHERE FIND_IN_SET("11",name)>
res2 = Author.objects.extra(where=[‘FIND_IN_SET(%s,name)‘],params=[‘11‘,])
# <QuerySet [<Author: 1,11,12>, <Author: 22,21,2,11>]>
所以如果list是常量,則直接用in;如果list是變量,則要使用find_in_set()函數。
SQL語句中find_in_set、like、in的區別及使用方法