在MySQL表

时间:2017-04-03 22:29:07

标签: mysql

我有一个包含结构和数据的表,如下所示。基本上,一个对象可以具有多个纬度和经度值。我想编写一个查询,获取同一行中对象的每个纬度/长对。

meta_id (PK) | object_id | key         | value
1            | 1         | latitude_0  | 10
2            | 1         | longitude_0 | 100
3            | 1         | latitude_1  | 11
4            | 1         | longitude_1 | 111
5            | 1         | latitude_2  | 12
6            | 1         | longitude_2 | 122

查询结果为

object_id | latitude | longitude
1         | 10       | 100
1         | 11       | 111
1         | 12       | 122

棘手的部分是可以有任意数量的纬度/长度对,所以我不能硬编码查询。一个物体可以有一对或者它可以有40对。我可以通过对JOINs进行硬编码来轻松获得结果,但这显然不是我想要的。我已在下面复制了我当前的查询,但无法配对相应的关键指标,例如:它将latitude_0longitude_0longitude_1longitude_2匹配。

SELECT p1.key, p1.value, p2.key, p2.value
FROM page_meta2 AS p1
    INNER JOIN page_meta2 AS p2 ON 
        p1.object_id = p2.object_id AND 
        p1.meta_id != p2.meta_id
WHERE p1.object_id = 1   -- will be parameter in final query (e.g. ?)
    AND p1.key LIKE 'latitude%'
    AND p2.key LIKE 'longitude%'

复制我的环境

复制环境的脚本是:

CREATE TABLE `page_meta` (
  `meta_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `object_id` bigint(20) unsigned NOT NULL DEFAULT '0',
  `key` varchar(255) DEFAULT NULL,
  `value` longtext,
  PRIMARY KEY (`meta_id`),
  KEY `object_id` (`object_id`),
  KEY `key` (`key`(191))
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `page_meta` ( `object_id`, `key`, `value`)
VALUES
    (1,'latitude_0', '10'),
    (1,'longitude_0','100'),
    (1,'latitude_1', '11'),
    (1,'longitude_1','111'),
    (1,'latitude_2', '12'),
    (1,'longitude_2','122'),
    (2,'latitude_0', '20'),
    (2,'longitude_0','200'),
    (2,'latitude_1', '21'),
    (2,'longitude_1','211'),
    (2,'latitude_2', '22'),
    (2,'longitude_2','222');

1 个答案:

答案 0 :(得分:2)

我会在连接条件中使用mysql' substring_index()函数来获取_字符后的数字,因此匹配纬度/经度对:

SELECT p1.object_id, p1.value as lat, p2.value as long
FROM page_meta2 AS p1
    INNER JOIN page_meta2 AS p2 ON 
        p1.object_id = p2.object_id AND 
        substring_index(p1.key, '_', -1) = substring_index(p2.key, '_', -1)
WHERE p1.object_id = 1   -- will be parameter in final query (e.g. ?)
    AND p1.key LIKE 'latitude%'
    AND p2.key LIKE 'longitude%'