This sounds like a cross table.
MySQL does not include a built-in function for cross tables, but you can build your cross table query "by hand".
Important: You must have a key to group the data. I'll assume that you have a place_id
column:
select max(case detail_key when 'location' then detail_value end) as location
, max(case detail_key when 'country' then detail_value end) as country
-- and so on
from places
-- add any WHERE conditions here
group by place_id
Hope this helps.
Edit
Your comment made me rethink your problem, and I found a solution here. Here is what you need to do:
- Create a variable that holds the expressions you want to apply to get what you need
- Create a valid SQL query
- Use a prepared statement when your query is ready.
I created a little SQL fiddle for you to see how to solve this, and here it is:
SQL Fiddle
MySQL 5.6 Schema Setup:
create table places(
id int unsigned not null auto_increment primary key,
place_id int,
detail_key varchar(50),
detail_value varchar(50)
);
insert into places (place_id, detail_key, detail_value) values
(1, 'location','Athens'),(1,'country','Greece'),(1,'longitude','12.3333'),(1,'weather','good');
Query 1:
set @sql = null
Results: (No results)
Query 2:
select group_concat(distinct
concat(
"max(case detail_key when '",
detail_key,
"' then detail_value end) as `",
detail_key,
"`"
)
)
into @sql
from places
Results: (No results)
Query 3:
set @sql = concat("select place_id, ", @sql, " from places group by place_id")
Results: (No results)
Query 4:
prepare stmt from @sql
Results: (No results)
Query 5:
execute stmt
Results:
| place_id | location | country | longitude | weather |
|----------|----------|---------|-----------|---------|
| 1 | Athens | Greece | 12.3333 | good |
Final edit
If you somehow created the above table with the data corresponding to just one place (i.e. there's no place_id
and all details are from a single place), you can do something like this:
select max(case detail_key when 'location' then detail_value end) as location
, max(case detail_key when 'country' then detail_value end) as country
-- and so on
from places
-- add any WHERE conditions here
group by null;