0

I am having a bit of a problem running a select query on a database. Some of the data is held as a list of comma separated values, an example:

Table: example_tbl

| Id | standardid | subjectid  |
| 1  | 1,2,3    |  8,10,3  |
| 2  | 7,6,12   |  18,19,2 |
| 3  | 10,11,12 |  4,3,7   |

And an example of the kind of thing I am trying to run:

select * from table where standardid in (7,10) and subjectid in (2,3,4)
select * from table  where FIND_IN_SET(7,10,standardid)  and FIND_IN_SET(2,3,4,subjectid)

Thanks in advance for anything you can tell me.

2
  • So - is it standardid or standard? Commented May 1, 2016 at 10:04
  • Note that searching this type of table will be very slow if the table is large. comma-separated values aren't indexed in any way that makes searching for items efficient. Commented May 1, 2016 at 11:44

1 Answer 1

1

comma separated values in a database are inherently problematic and inefficient, and it is far, far better to normalise your database design; but if you check the syntax for FIND_IN_SET() it looks for a single value in the set, not matches several values in the set.

To use it for multiple values, you need to use the function several times:

select * from table
 where (FIND_IN_SET(7,standardid)
     OR FIND_IN_SET(10,standardid))
   and (FIND_IN_SET(2,subjectid)
     OR FIND_IN_SET(3,subjectid)
     OR FIND_IN_SET(4,subjectid))
Sign up to request clarification or add additional context in comments.

4 Comments

in dynamic way like $a= "2,3,4"
You'd have to split $a into an array of individual values, and build your query for each value in that array
I am getting values from form post sir.
Then you build your query by iterating over the relevant values in $_POST... I've shown you what the query should look like.... I've also recommended that you normalise your database properly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.