简体   繁体   中英

Select value inside a comma separated string mysql

This is something I have been thinking for hours and still cant get the answer.

So, I have this mysql table called 'orders'

+-----------------------------+
+ id | include                +
+-----------------------------+
+  1 | 4,7,9                  +
+  2 | 1,23,8                 +
+  3 | 11,6,3                 +                 
+  4 | 2,56,32,6              +
+-----------------------------+

I want to select a row when I have one number in the include column.

For example I have tried with this:

SELECT *  FROM `orders` WHERE `include` LIKE '%1%'

But the problem is it selects both rows 2 and 3 because number '11' contains '1'.

I need two querys: when the include table contains 'x', and when the include table does not contain 'x'.

Does anyone know how to do this?

Use FIND_IN_SET()

SELECT *  FROM `orders` 
WHERE find_in_set(1, `include`) > 0

But generally it would be way better to change the table structure and store only one value in the column. It' the third rule of DB normalization.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM