Select row which contains exact number in column w

2019-06-24 01:39发布

Maybe answer is very easy, but I can't find the right MySQL query which do what I want.

I have table user :

| id_user |  name   | action_type |
+---------------------------------+
|    1    | joshua  |  1,13,12,40 |
|    2    | joshua  |  2,8        |

And I want to select only rows which have exact number in action_type column.

action_type is stored in MySQL as TEXT.

I've tried this:

SELECT * FROM user WHERE action_type LIKE '%2%'

But it selected rows with 12 which is not what I want :(

Maybe it's possible with IN operator, but I couldn't find a right way to use this.

3条回答
姐就是有狂的资本
2楼-- · 2019-06-24 02:23

You are looking for FIND_IN_SET

SELECT *
FROM user
WHERE FIND_IN_SET( '2', action_type )

SQL Fiddle DEMO

UPDATE

Just to mentioned it, this is also possible

SELECT *
FROM user
WHERE FIND_IN_SET( 2, action_type )

MySQL will do an automatic conversion to char

查看更多
Bombasti
3楼-- · 2019-06-24 02:26

Try

SELECT * FROM user
WHERE CONCAT( ',', action_type, ',' ) LIKE '%,2,%';
  • correct syntax from Sir Rufo
查看更多
不美不萌又怎样
4楼-- · 2019-06-24 02:29

Include the delimiter in your LIKE clause:

SELECT *
FROM   user
WHERE  action_type LIKE '2,%'
        OR action_type LIKE '%,2,%'
        OR action_type LIKE '%,2'

Note that I had to use two additional LIKE clauses to cover the cases where the item is at the beginning or end of the string.

查看更多
登录 后发表回答