2

I have two tables in my db

posts table (id,title,data) and tags table (id,post_id,tags)

Example data in tags table

Example data in tags table:

id  post_id tag
1   1   PHP
2   1   JS
3   2   C
4   2   C++
5   2   MySql

Posts table

id title date
1  post1 12/05/2015
2  post2  12/05/2016

I want an output like this

Example output:

id  title   tags
1   Post1   PHP, JS
2   Post2   C, C++,MySql

How can i write one single query obtain the result like this

Currently i performs a left join

SELECT * FROM  posts  LEFT JOIN tags ON tags.post_id=posts.id GROUP BY tags.post_id

I know group concat is used to obtain this result but i don't know how to use it

5
  • what you want to do with group by ? Commented Jun 13, 2017 at 8:37
  • I got confused with group by Commented Jun 13, 2017 at 8:38
  • See: Why should I provide an MCVE for what seems to me to be a very simple SQL query? Commented Jun 13, 2017 at 8:40
  • Thanks for the progress report. Commented Jun 13, 2017 at 8:43
  • @BlessanKurien I think my answer will help you to join with comma seperated Commented Jun 13, 2017 at 8:46

1 Answer 1

1

use group GROUP_CONCAT to get result as a comma separated value:

SELECT posts.id
     , posts.title
     , GROUP_CONCAT(tags.tag) 
  FROM  posts  
  LEFT 
  JOIN tags 
    ON tags.post_id = posts.id  
 GROUP 
    BY posts.id
Sign up to request clarification or add additional context in comments.

Comments

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.