将单列数据合并到php

时间:2016-10-01 01:05:46

标签: php mysql

我在一个表中有600行数据,表结构是

表名:city_Data

------------------------------
cityId  |   cityName
------------------------------
1   |   chennai
2   |   madurai
3   |   trichy
4   |   kovai
...
...
...
------------------------------

cityId - autoincrement

现在我想将这个表数据和插入混合到另一个表中。此表的名称是city_Mix。

---------------------------------------
mixId   |   city1   |   city2
---------------------------------------
1   |   chennai |   madurai
2   |   chennai |   trichy
3   |   chennai |   kovai
4   |   madurai |   chennai
5   |   madurai |   trichy
6   |   madurai |   kovai
7   |   trichy  |   chennai
...
...
...
---------------------------------------

这里,city1和city2是should not be same和mixId - autoincrement

怎么做?任何人PLZ帮我提供示例代码..

2 个答案:

答案 0 :(得分:2)

尝试以下查询,该查询使用join来组合不匹配的城市名称并将dat插入到city_mix表中

NOW()                      CURDATE()    CURTIME()
2014-11-22 12:45:34       2014-11-22    12:45:34

http://sqlfiddle.com/#!9/2e01ea/3

答案 1 :(得分:2)

我正在对你具体提出的问题做出一些假设,如果你要提供更多可能有帮助的信息:

  1. city_Mix是否已包含字段city2,或者您希望从city_Data加入的列?
  2. 你是用PHP还是SQL做这个?
  3. city_Mix真的是city_Data表的自我迭代吗?
  4. 您提供的数据是代表数据库表还是PHP数据结构?
  5. 再一次,我在这里做了一些假设,但我会根据你提供的内容尝试帮助......

    city_Mix似乎与我的问题列表中的#3 相匹配(因此您想要获取项目列表,并且对于列表中的每个项目,将其映射到所有其他项目在名单上)。如果这个假设是正确的,这是解决方案的一种方法:

    使用SQL

    //您可能希望使用INNER JOIN快速完成此操作,如下所示

    (SELECT 'cityName' FROM `city_Data` c INNER_JOIN `city_Data` m ON m.cityName != c.cityName)
    

    使用PHP

    仅供参考:我建议不要使用SQL来支持这一点,但是希望将其作为“一种方法”,因为您没有说明您接近解决方案的方式。

    <?php
    
    $cityMixData = []; //Final data table as you've indicated you desire
    
    //Connect to your database
    $con = mysql_connect("localhost","inmoti6_myuser","mypassword");
    if (!$con)
    {
      die('Could not connect: ' . mysql_error());
    }
    mysql_select_db("databaseName", $con);
    
    // Define our SQL query
    $query = "SELECT DISTINCT `cityName` FROM `city_Data` ORDER BY `cityId`";
    
    // Execute the query
    $cities = mysql_query($query);
    
    $i = 1; // Iterator index
    $cityMixData = [];
    // Loop through the list of unique city names and map all other items accordingly
    while( $city = mysql_fetch_array( $cities, MYSQL_ASSOC ) ) {
        $tmpArr = $cities;
        unset($tmpArr[$row[$i - 1]); // Remove self
        $cityMap = array_values($tmpArr); // reindex array
        $mixRow = array($mixId => $i, $city1 => $city['cityName'], $city2 => $cityMap); // Create a row with auto-increment ID, city1 === unique city name, city2 === list of unique cities sans-city1
        $cityMixData[] = $mixRow; // Add row to cityMixData which is multi-dimensional array
        $i++; // Increment iterator
    }
    
    // Connect to DB
    // Create city_Mix table if not exist
    // Appropriately generate SQL based on $cityMixData structure, might get messy
    // Save to DB
    ?>
    

    如果你回答我上面提出的问题,我将能够提供更多帮助。