Welcome to my blog, hope you enjoy reading
RSS

Saturday 4 January 2014

One table comma(,) separated values to get another table data in mysql

One table comma(,) separated values to get another table data in mysql

problem:

I have two tables:

Posts Table

PostID | Gallery
  1    | 4,7,8,12,13
  2    | 1,2,3,4
  3    | 5,8,9
  4    | 3,6,11,14
The values in Gallery are the primary keys in the Images table:

Images Table


ImageID | FileName
   1    | something.jpg
   2    | lorem.jpg
   3    | ipsum.jpg
   4    | what.jpg
   5    | why.jpg

How can i get FileName of PostID is 2;

result:
FileName
something.jpg
lorem.jpg
ipsum.jpg
 what.jpg

solution:
You can use this solution:
  • SELECT b.filename FROM posts a INNER JOIN images b ON FIND_IN_SET(b.imageid, a.gallery) > 0 WHERE a.postid =2

0 comments: