0

I have two tables as follows.

Category table
+------------+------------+--------------+
| CategoryID | Name       | CategoryCode |
+------------+------------+--------------+
|          1 | Fixed      |              |
|          2 | Consumable |              |
|          3 | Intangible |              |
+------------+------------+--------------+

Type table
+--------+------------+-------------------------+----------+
| TypeID | CategoryID | Name                    | TypeCode |
+--------+------------+-------------------------+----------+
|      1 |          1 | Furniture               |          |
|      2 |          1 | Computers & Peripherals |          |
|      3 |          2 | Keyboards               |          |
|      4 |          2 | Other                   |          |
|      5 |          3 | Software                |          |
+--------+------------+-------------------------+----------+

The result I want is like this

+------------+------------+------------------------------------+
| CategoryID | Category   | Types                              |
+------------+------------+------------------------------------+
|          1 | Fixed      | Furniture, Computers & Peripherals |
|          2 | Consumable | Keyboards, other                   |
|          3 | Intangible | Software                           |
+------------+------------+------------------------------------+

Appriciate if you could help me with wirting the query in MySQL

1
  • Read up on the basics of JOINS, if you are unfamiliar - and then go check out GROUP_CONCAT. Commented Sep 28, 2021 at 8:44

1 Answer 1

2

You can try this solution

SELECT
    a.CategoryId,
    a.`Name` Category,
    GROUP_CONCAT(b.`Name`) Types
FROM
    Category a
INNER JOIN Type b ON b.CategoryID = a.CategoryId 
GROUP BY a.CategoryId
Sign up to request clarification or add additional context in comments.

3 Comments

I'd also put a.Name in the GROUP BY, to ensure MySQL forward compatibility.
@Plantour this will not work with sql_mode=only_full_group_by in order to work. You need all the columns in the select part of the group by or to be an aggregation function like MAX, SUM
@Plantour that is what @jarlh meant on the comment, your group by should be : group by a.CategoryId ,a.Name; Demo: db-fiddle.com/f/7yUJcuMJPncBBnrExKbzYz/89

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.