1

Table A:

id        name        desc
--------------------------------
1        abc        something

2        xyz        something

Table B:

id        nameB        descB        tableA(fk)
-----------------------------------------------
1        ghj        something          1

2        jkl        somethingxyz       1

3        sdf        somesdf            2

4        dfg        somedfg            2

I was able to produce output like

TableA.name TableB.name - Count(TableB.name)

abc              ghj - 1
abc              jkl - 1
xyz              sdf - 1
xyz              dfg - 1

But i want something like this

TableA.name TableB.name - Count(TableB.name)

abc              ghj - 1, jkl - 1
xyz              sdf - 1, dfg - 1 

1 is count

Pls help with mysql query.

1
  • Seriously consider handling issues of data display in application code Commented May 18, 2021 at 11:06

1 Answer 1

2

You can try to use GROUP_CONCAT function with GROUP BY

Query 1:

SELECT A.name,
       GROUP_CONCAT(CONCAT(b.nameB,'-',cnt) SEPARATOR ',') 
FROM A 
INNER JOIN (
    SELECT  tableA,nameB,COUNT(*) cnt
    FROM B
    GROUP BY tableA,nameB
) b ON A.id = b.tableA
GROUP BY A.name

Results:

| name | GROUP_CONCAT(CONCAT(b.nameB,'-',cnt) SEPARATOR ',') |
|------|-----------------------------------------------------|
|  abc |                                         ghj-1,jkl-1 |
|  xyz |                                         dfg-1,sdf-1 |
Sign up to request clarification or add additional context in comments.

3 Comments

will it be same for sqlite?
Almost the same but it is a little difference on concat string syntax db-fiddle.com/f/cAbFkvTNJJgRYjYYvEbPxe/0
What if i have single table?

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.