Question

I have done searching, but everything I have found is reverse the way I need.

I have a database where one of the fields is a string of IDs, I want to search for a certain ID in that array I have in the DB already.

For instance, in the database it looks like this:

ID    Title    Spots Used
 1    test 1    1,3,5,8
 2    test 2    4,2,5,6,7
 3    test 3    3,5,2,1

I need to search for how many campaigns were used that have the spot that has the ID of 2 (should return both test 2 and test 3).

What would be the best way to go about this? So far, I can query the entire thing, run row by row, and do a strpos search for the number, but the problem is that when I end up getting more than 10 spots uploaded, 1 will return 1, 10, 11, 12, 13, etc.

If I need to provide more info, please let me know.

Was it helpful?

Solution

If these ids are stored as comma seperated then you can use FIND_IN_SET()

SELECT * FROM `table` WHERE FIND_IN_SET('2',`column_name`) >0

But storing comma separated values is bad idea if you are able to change your schema then first normalize your table structure

Database Normalization

OTHER TIPS

You can have everything in just one table but c'mon what is it good for a relational database,

create two more tables , one will be Spot(id,spot_number) an the other one Campaigns_spot(id_campaign,id_spot), and the let the sql engine do it with a query , this way is far more efficient and you are going to be using a proper database relation.

the query then would be

select count(*) from campaign_spot where id_spot= X (whatever number you want).
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top