5

I want to join multiple row values from table.

Table name:Item

    ID |            item_id |     Value
    1               43          item1
    2               44          item2
    3               44          item3
    4               44          item4
    5               45          item5
    6               45          item6

ID's are unique (primary key) What I am looking to output is a mysql query is something to which gives this output as given below

Output:

  ID |            item_id |     Value
    1               43          item1
    2               44          item2,item3,item4
    3               44          item2,item3,item4
    4               44          item2,item3,item4
    5               45          item5,item6
    6               45          item5,item6

kindly requesting to give some suggestions

3
  • You can use GROUP_CONCAT() to do that. Commented Feb 25, 2016 at 5:15
  • Possible duplicate of How to use GROUP BY to concatenate strings in MySQL? Commented Feb 25, 2016 at 5:20
  • here ID 's are unique Commented Feb 25, 2016 at 5:21

4 Answers 4

2

Try this query:

SELECT t1.ID, t1.item_id, t2.Value
FROM item t1
INNER JOIN
(
    SELECT item_id, GROUP_CONCAT(Value) AS Value
    FROM item
    GROUP BY item_id
) t2
    ON t1.item_id = t2.item_id

Follow the link below for a running demo:

SQLFiddle

Sign up to request clarification or add additional context in comments.

Comments

0

You can use self join with subquery of group_concat

SELECT    i.ID, i.item_id, subquery.`new_value` as value
FROM item i 
JOIN (
    SELECT item_id, GROUP_CONCAT(`Value`) as new_value
    FROM item 
    GROUP BY item_id;
)as subquery 
ON  subquery.item_id = i.item_id;

Comments

0

You can use below query.

SELECT GROUP_CONCAT(value) FROM Item GROUP BY item_id;

Comments

0

Try this Query

  SELECT t1.ID, t1.item_id,
      (
        SELECT GROUP_CONCAT(t2.Value) FROM item AS t2
        WHERE t1.item_id = t2.item_id
        GROUP BY t2.item_id
      ) AS Value
 FROM item AS t1

Demo http://sqlfiddle.com/#!9/bbc20/18/0

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.