2

Table 1:

id   | typeid | available|
0    | 1      | 12       |
0    | 2      | 44       |

Table 2:

typeid   | typename   |
1        | CL          |
2        | ML          |

I have a query using concat and group_concat:

select id,concat(group_concat(typename,available)) as types from table1
join table2 on table2.typeid=table1.typeid

I got the result as:

id | types   | 
0  | CL12,ML44 |

But I want to display it like this:

id   | CL   | ML    |
0    | 12   | 44    |

Is there any way to split the group_concat result to columns heads?

I want dynamically fetch data from table2. Some user can add data to table2. So hard-coding typename is not possible.

Justin
  • 9,634
  • 6
  • 35
  • 47
noushad
  • 165
  • 2
  • 3
  • 11

3 Answers3

4

You should use table pivoting. There is no PIVOT command in MySQL, so you can use this query -

SELECT
  t1.id,
  MAX(IF(t2.typename = 'CL', t1.available, NULL)) AS CL,
  MAX(IF(t2.typename = 'ML', t1.available, NULL)) AS ML
FROM table1 t1
  JOIN table2 t2
    ON t1.typeid = t2.typeid
GROUP BY
  t1.id;

MySQL pivot tables (transform rows to columns).

Use GROUP_CONCAT function instead of MAX, if multiple available values are possible.

Devart
  • 119,203
  • 23
  • 166
  • 186
  • But now a challenge: How about if you don't know the typename values? Is it at all possible then? – Jos May 20 '16 at 10:50
0

Try this:

SELECT a.id, MAX(IF(b.typename = 'CL', a.available, 0)) CL, 
       MAX(IF(b.typename = 'ML', a.available, 0)) ML
FROM table1 a
INNER JOIN table2 b ON a.typeid=b.typeid
GROUP BY a.id;

Use SUM function if you want to sum of the data from available column for particualr type else use the same query as ii is.

Saharsh Shah
  • 28,687
  • 8
  • 48
  • 83
0

It can be done only if you know all the typenames in advance -- otherwise, you'll need to find another way. In databases that support returning result sets from stored procedures, it could be done with a stored proc. But mysql doesn't support that.

If you know all the typenames, here's how you build the query:

SELECT
    id,
    SUM(IF(typename = 'CL', available, 0)) AS `CL`,
    SUM(IF(typename = 'ML', available, 0)) AS `ML`
FROM table1 join table2 on table1.typeid = table2.typeid
GROUP BY id
Lee
  • 13,462
  • 1
  • 32
  • 45