Mysql从两个表中选择组相似的行

时间:2014-05-13 17:20:53

标签: php mysql sql

如果有人可以帮我解决问题,我真的很感激。

我有两个mysql表:

城市(约90,000行)

|         ID(primaryKey)         |  CITY_ID |  SUPPLIER   |
|3fe07eaec62d209c1c153bd3e5501ac5|  xxxxxx  |  supplier1  |
|2a3eaad85c0e7ebb1f7ddaf9a423d808|  yyyyyy  |  supplier2  |
|c47376be023028eb17addcd5813cf592|  zzzzzz  |  supplier3  |
|f4d2b3a0da4d6bad0c89ad2471bd1dd7|  kkkkkk  |  supplier1  |

City_Translates(约500,000行)

|               ID               |  CITY    |  COUNTRY        | LANGUAGE |
|3fe07eaec62d209c1c153bd3e5501ac5|  LONDRA  |  Gran Bretagna  |    IT    |
|3fe07eaec62d209c1c153bd3e5501ac5|  LONDON  |  Great Britain  |    EN    |
|3fe07eaec62d209c1c153bd3e5501ac5|  LONDON  |  Großbritannien |    DE    |
|c47376be023028eb17addcd5813cf592|  LONDON  |  Great Britain  |    EN    |
|c47376be023028eb17addcd5813cf592|  LONDRA  |  Gran Bretagna  |    EN    |
|2a3eaad85c0e7ebb1f7ddaf9a423d808|  ROMA    |  ITALIA         |    IT    |
|2a3eaad85c0e7ebb1f7ddaf9a423d808|  ROME    |  ITALY          |    EN    |

我需要的是创建一个php脚本来对这两个表进行分组,以便得到这样的结构:

[
{"translates":
  {
    "it":{"city":"LONDRA","country":"Gran Bretagna"},
    "en":{"city":"LONDON","country":"Great Bretain"},
    "de":{"city":"LONDON","country":"Großbritannien"}
  },
 "suppliers":
  {
     "supplier1":"xxxxxx",
     "supplier2":"zzzzzz"
  }
},
{"translates":
  {
    "it":{"city":"ROMA","country":"ITALIA"},
    "en":{"city":"ROME","country":"ITALY"}
  },
 "suppliers":
  {
     "supplier1":"yyyyyy"
  }
},...]

我这样做是因为我需要将该结构导入到noSQL数据库中,所以这个操作必须只进行一次。

有人可以给我一个解决方案吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

我很困惑为什么LONDON/Great Britain引用了不同的城市ID(主键)。无论如何,我假设您想要通过城市字符串和城市ID(pk)的组合进行分组,因为您的示例每个组有多个供应商。

即。我们知道LONDONLONDRA属于同一个群组,因为它们具有相同的密钥。当他们再次看到不同的密钥时,我们知道他们属于同一个群组,因为我们之前遇到过这些城市名称。

这里有一个镜头:)

$query = "SELECT * FROM Cities c 
JOIN City_Translates ct ON ct.ID = c.ID
ORDER BY ID"; //order by is necessary so all like cities end up in the same group

$rs = mysqli_query($query) or die(mysqli_error());

$results = array();
$city_id = array(); // lookup id by city name
//used to group like cities

while($r = mysqli_fetch_assoc($rs)) {

    //if we've seen this city before grab
    //the city id (pk) where we store its data
    if(isset($city_id[$r['CITY']])) {
        $id = $city_id[$r['CITY']];
    }
    else { //otherwise store the city id (pk) for this city
        $city_id[$r['CITY']] = $r['ID'];
        $id = $r['ID'];
    }

    $results[$id]['translates'][$r['LANGUAGE']] = array(
        'city' => $r['CITY'],
        'country' => $r['COUNTRY'],
    );

    $results[$id]['suppliers'][$r['SUPPLIER']] = $r['CITY_ID']; 
}

$results = array_values($results); //remove ID keys
print json_encode($results,JSON_PRETTY_PRINT);