Log in

View Full Version : Select IN table



Master_script_maker
10-24-2009, 11:29 PM
I am setting up a blog system, and am having trouble setting up categories. I have a table, blog_posts, which stores information about the post. There is a column, post_sections, which stores an imploded array of the sections' ids eg: 0,1,2,3,4. Now if I want to select posts by section 0, I try SELECT * FROM `blog_posts` WHERE 0 IN (`post_sections`), but this only works if the first of the array is 0 eg: 0,1,2,3 but not if it is somewhere else eg 1,2,4,0,7. Is there anyway I can make this work?
Thanks

traq
10-25-2009, 04:39 PM
have you tried SELECT * FROM `blog_posts` WHERE '0' IN (`post_sections`) ?

Master_script_maker
10-25-2009, 05:00 PM
that gives me an empty result set

traq
10-25-2009, 06:11 PM
We've got it backwards:


// CORRECT
SELECT * FROM `blog_posts` WHERE `post_sections` IN ('0')

// INCORRECT
SELECT * FROM `blog_posts` WHERE 0 IN (`post_sections`)

however, I think what you actually want is a LIKE statement:

SELECT * FROM `blog_posts` WHERE `post_sections` LIKE '%0%'
(see example here (http://www.custom-anything.com/test2.php))


of course, that will return " 10 " and " 105 " as well as " 0 ".
As you can see in my example, '%h%' returns all the "home" rows but also an extra one - that row has a "parent" value of "archive".
maybe redesign your post_sections fields to start and end with a comma as well, like so: ,0,1,2,3,4,
then you could write your statement like this:

SELECT * FROM `blog_posts` WHERE `post_sections` LIKE '%,0,%'
and get only rows with " 0 "

Master_script_maker
10-25-2009, 06:25 PM
wow thanks, it works :)

traq
10-25-2009, 06:39 PM
glad I could help :) I think you replied before I finished my edit above. You may want to check it out.

Master_script_maker
10-25-2009, 06:41 PM
yeah, I did, but I noticed it after i posted