Select row which contains exact number in column w

2019-06-24 02:25发布

问题:

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.

回答1:

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



回答2:

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.



回答3:

Try

SELECT * FROM user
WHERE CONCAT( ',', action_type, ',' ) LIKE '%,2,%';
  • correct syntax from Sir Rufo