How to use FIND_IN_SET in MySQL?

爷,独闯天下 提交于 2019-12-11 16:16:15

问题


How to use FIND_IN_SET,

The values I have is

|       Val         |
| No, 1, Yes,5, O, 4|

I tried doing

FIND_IN_SET('No', Val)

And got the value of 1 and then I tried:

FIND_IN_SET('No', Val) as 'No', FIND_IN_SET('Yes', Val) as ''Yes'

But got the output

|   No  |   Yes |
|   1   |   0   |

How come it suddenly can't find the 'Yes' in the text?

Another format:

| Val   |
| No, 1, 
  Yes,5, 
  O, 4   |

Note: This is not on 3 rows, just on one row but using the next line(line breaks) for the other values


回答1:


Because the actual value in your string is ' Yes' (with a space)

This will work

SELECT FIND_IN_SET(' Yes',Val) FROM test

Fiddle

But then it wont work if Yes is the first value without space. You can do this for a general case scenario (a little expensive though)

SELECT FIND_IN_SET('Yes',REPLACE(Val," ","")) FROM test

Fiddle




回答2:


Because 'Yes' is not in that set. However, ' Yes' is.

Run:

SET @foo = 'No, 1, Yes,5, O, 4';
SELECT
  FIND_IN_SET('No', @foo),
  FIND_IN_SET('Yes', @foo),
  FIND_IN_SET(' Yes', @foo);

Result set: 1,0,3




回答3:


This function returns the position of the string. You can easily understand the use of FIND_IN_SET with this tutorial -

http://phpforweb.info/how-to-use-find_in_set-in-mysql-query/



来源:https://stackoverflow.com/questions/25330946/how-to-use-find-in-set-in-mysql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!