简体   繁体   中英

SQL query to match multiple values in a single column

This dummy table:

name | lesson_mode
-------------------

a    | 1,2,3
b    | 2,3 
c    | 2
d    | 3

Using this query:

SELECT * FROM `cc_teacher` WHERE lesson_mode IN (2,3)

I get

name | lesson_mode
-------------------

b    | 2,3 
c    | 2
d    | 3

I am having a problem in search results, my problem is that suppose, in this case we are talking about lesson_mode column, I have written the SQL query like this:

SELECT * FROM `cc_teacher` WHERE lesson_mode IN (2,3) 

but I didn't get the row in which have 1,2,3 , so please help me. Anyone know how to do that?

The best help for you is advice to fix your data structure. You should have a table that is TeacherLessons with one row per teacher and one row per lesson. SQL has a great data structure for storing lists. It is called a "table", not a "string". And, worse, you are storing numeric ids as character strings.

You can do what you want using find_in_set() . It would look like:

select *
from cc_teacher
where find_in_set(2, lesson_mode) > 0 or
      find_in_set(3, lesson_mode) > 0;

But my main advice is for your to fix our database structure by introducing a junction table.

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