MySQL数据处理。如何从数据库斜杠后获取值

时间:2014-10-21 14:39:50

标签: php mysql json

我正在城镇内的城镇和地区的MySQL数据库中处理一些数据。

数据库看起来像这样

ID | NAME
1  | Manchester
2  | Manchester/North
3  | Manchester/South
4  | Manchester/East
5  | Manchester/West

我尝试过一个PHP脚本,它只会找到/之后的单词,并根据计数变量$j生成一个数字,但到目前为止还无效。稍后我计划将其写入变量$data来自的JSON文件中。

我的理想输出为north south east west 4

这是脚本

$j=0;
foreach($data->objects->layer->geometries as &$h)
{
   foreach($result as $row)
   {
     preg_match("/[^\/]+$/", $row['name'], $matches); // Town/Region
     $no_slash = $matches[0]; // Region
     if(strtolower($h->properties->name) == $no_slash)
     {
        $h->properties->id = $row['id'];
        $j++;

        echo $j . " " . $no_slash . "<br />";
     }
 } 
} 

echo "Number of matches: " . $j;

我目前的输出是Number of matches: 0有没有人知道为什么?

2 个答案:

答案 0 :(得分:0)

如果我理解你的问题,你可以使用这个MySQL查询:

SELECT
  SUBSTRING_INDEX(NAME, '/', 1) AS city,
  GROUP_CONCAT(SUBSTRING_INDEX(NAME, '/', -1) SEPARATOR ' ') AS districts,
  COUNT(*) AS cnt
FROM
  tablename
WHERE
  NAME like '%/%'
GROUP BY
  city

请参阅小提琴here

答案 1 :(得分:0)

示例数据:

CREATE TABLE t
    (`ID` int, `NAME` varchar(16))
;

INSERT INTO t
    (`ID`, `NAME`)
VALUES
    (1, 'Manchester'),
    (2, 'Manchester/North'),
    (3, 'Manchester/South'),
    (4, 'Manchester/East'),
    (5, 'Manchester/West');

查询:

SELECT
SUBSTRING(Name, 1, LOCATE('/', Name) - 1) Town,
CONCAT(GROUP_CONCAT(SUBSTRING(Name, LOCATE('/', Name) + 1)), ': ', COUNT(*)) AS Regions
FROM t
WHERE Name LIKE '%/%'
GROUP BY Town;

输出:

|       TOWN |                  REGIONS |
|------------|--------------------------|
| Manchester | North,South,East,West: 4 |