How to convert a column data to a row in php mysql

419 views Asked by At

This is basically for testing an address book php application. Here is the output I got from the SQL query. I want to convert this results to a row.

MySQL Query output

SQL Query output

Output looking for

enter image description here

2

There are 2 answers

0
Ullas On BEST ANSWER

Query

SELECT contact_id,
MAX(First_name) AS First_name,
MAX(Last_Name) AS Last_Name,
MAX(Primary_Email) AS Primary_Email,
MAX(Primary_phone) AS Primary_phone
FROM (
SELECT MIN(contact_id) as contact_id,
CASE WHEN meta_data='First_Name' THEN meta_value END AS First_Name,
CASE WHEN meta_data='Last_Name' THEN meta_value END AS Last_Name,
CASE WHEN meta_data='Primary_Email' THEN meta_value END AS Primary_Email,
CASE WHEN meta_data='Primary_phone' THEN meta_value END AS Primary_phone
FROM tbl
GROUP BY contact_id,meta_data,meta_value
) t
GROUP BY contact_id

Fiddle demo

0
Domain On

Try following query. Suppose postmeta is a table name

select a.contact_id,b.meta_value,c.meta_value,d.meta_value,e.meta_value
from postmeta a 
join postmeta b on (a.contact_id=b.contact_id and b.meta_date='First_Name')
join postmeta c on (a.contact_id=c.contact_id and c.meta_date='Last_Name')
join postmeta d on (a.contact_id=d.contact_id and d.meta_date='Primary_Email')
join postmeta e on (a.contact_id=e.contact_id and d.meta_date='Primary_Phone')