以不同列的单行分组

时间:2013-08-28 15:22:56

标签: mysql sql performance

SCENARIO

id | location_id | coordinate_type | value
 1 |           1 | lat             | 17.3111
 2 |           1 | lng             | 45.5293978
 3 |           2 | lat             | 37.3111
 4 |           2 | lng             | 21.4646422
 5 |           3 | lat             | 37.3451
 6 |           3 | lng             | 25.529648
 7 |           4 | lat             | 37.3111
 8 |           4 | lng             | 13.688902
 9 |           5 | lat             | 37.3111
10 |           5 | lng             | 22.523535

QUERY RESULT:

location_id | lng            | lat
          1 | 45.5293978     | 17.3111
          2 | 21.4646422     | 37.3111
          3 | 25.529648      | 37.3451
          4 | 13.688902      | 37.3111
         ...

如何以最佳表现获得结果?

2 个答案:

答案 0 :(得分:2)

试试这个

select location_id
,MAX(CASE WHEN coordinate_type = 'lng' THEN value ELSE NULL END) AS 'lng'
, MAX(CASE WHEN coordinate_type = 'lat' THEN value ELSE NULL END) AS 'lat'
from Table1
GROUP BY location_id

SQL FIDDLE DEMO

答案 1 :(得分:0)

您可以在(coordinate_type, location_id, value)上添加索引,然后尝试此查询:

SELECT 
    t_lat.location_id ,
    t_lat.value AS latitude ,
    t_lng.value AS longitude 
FROM 
    tableX AS t_lat
  JOIN
    tableX AS t_lng
      ON t_lat.location_id = t_lng.location_id
WHERE
    t_lat.coordinate_type = 'lat'
  AND
    t_lng.coordinate_type = 'lng' ;