Q:

multiple attribute query from mysql

i have a question here... i have a 3 tables like this...
customer
idCustomer | namaCustomer | email   | noTelp 
__________________________________________________
1          |  Wawan       | a@a.com | 08985623895

attribute
idAttribute | Name   | publish
______________________________
1           | Gender |  Y
2           | Hobby  |  Y
3           | Job    |  Y
4           | Mission|  N

Customer attribute
idCustomer  |  idAttribute   | value 
_____________________________________
1           |   1            | Male
1           |   2            | Hacking
1           |   3            | IT Support

The question is.. what query statement if i want to get the query from that 3 tables and get the result like this
idCustomer | namaCustomer | email   | noTelp      | Gender  | Hobby   | Job
___________________________________________________________________________________
1          |  Wawan       | a@a.com | 08985623895 | Male    | Hacking | IT Support

So the table column was added from customer attribute data, but before that we must look attribute tabel that the attribute is published or not (looking for publish value) 
anyone can help me here???
great thanks before

A:

Try this:
SELECT
  c.idCustomer,
  c.namaCustomer,
  c.email,
  c.noTelp, 
  MAX(CASE WHEN a.Name = 'Gender' THEN ca.value END) AS 'Gender',
  MAX(CASE WHEN a.Name = 'Hobby'  THEN ca.value END) AS 'Hobby',
  MAX(CASE WHEN a.Name = 'Job'    THEN ca.value END) AS 'Job'
FROM Customerattribute ca
INNER JOIN attribute a ON ca.idAttribute = a.idAttribute
INNER JOIN Customer c ON c.idCustomer = ca.idCustomer
GROUP BY ca.idCustomer

SQL Fiddle Demo
However, for future use of this query for new attributes, you have to do it dynamically like so:
SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT CONCAT('MAX(IF(a.Name = ''',
      a.Name, ''', ca.value, NULL)) AS ',
      a.Name )
  ) INTO @sql
FROM Customerattribute ca
INNER JOIN attribute a ON ca.idAttribute = a.idAttribute
INNER JOIN Customer c ON c.idCustomer = ca.idCustomer
WHERE a.publish = 'Y';

SET @sql = CONCAT('SELECT  c.idCustomer,  c.namaCustomer, '
  ' c.email, c.noTelp, ', @sql, ' FROM Customerattribute ca',
 ' INNER JOIN attribute a ON ca.idAttribute = a.idAttribute', 
' INNER JOIN Customer c ON c.idCustomer = ca.idCustomer',
' GROUP BY c.idCustomer');

SELECT @sql;

prepare stmt 
FROM @sql;

execute stmt;

Dynamic Fiddle Demo

