插入两行与配对id mysql php

时间:2013-09-28 05:32:05

标签: php mysql sql match

我有一个问题:

SELECT * FROM match ORDER BY id ASC

结果将包含以下内容:

ID Name   Age
1  Mary   18
2  Edward 18
3  Jen    22

我想和Mary和Edward结对,因为他们的年龄相同: 预期结果将是:

1. Mary
      ID 1 Age 18 match to ID 2 Edward Age 18
2. Edward
      ID 2 Age 18 match to ID 1 Mary Age 18
3. Jen
      ID 3 Age 22 match to no pair

我想连续两次插入该对,并且对应一对。

这是我的代码:

$result = mysql_query("SELECT * FROM match ORDER BY id ASC");
$size_of_array = sizeof($result);
$i = 1;
while($data = mysql_fetch_row($result)) {
     $pair_A  = $data[0];
     while ($i <= $size_of_array) {
            $pair_B  = $data[$i];

            $insert_A = array(
                              'id'  =>  $pair_A['id'],
                              'name' => $pair_A['name'],
                              'age'  => $pair_A['age'],
                              'partnerName' => $pair_B['name'],
                              'partnerAge'  => $pair_B['age']
                              'partnerID'   => $pair_B['id']
                              );
            //insert statement 1
            $insert_B = array(
                              'id'  =>  $pair_B['id'],
                              'name' => $pair_B['name'],
                              'age'  => $pair_B['age'],
                              'partnerName' => $pair_A['name'],
                              'partnerAge'  => $pair_A['age']
                              'partnerID'   => $pair_A['id']
                              );
            //insert statement 2

            //Remove duplicates
            unset($pair_A);
            unset($pair_B);
            $i++;
     } 
}

还有其他任何建议或代码可以轻松实现吗?

1 个答案:

答案 0 :(得分:0)

如果我理解正确,你可以用一个陈述

来完成
INSERT INTO match_pairs (ID, Name, Age, PartnerID, PartnerName, PartnerAge)
SELECT m1.id, m1.name, m1.age,
       m2.id partnerid, m2.name partnername, m2.age partnerage
  FROM `match` m1 LEFT JOIN `match` m2
    ON m1.age = m2.age AND m1.id <> m2.id
 ORDER BY m1.id

结果为match_pairs

+------+--------+------+-----------+-------------+------------+
| ID   | Name   | Age  | PartnerID | PartnerName | PartnerAge |
+------+--------+------+-----------+-------------+------------+
|    1 | Mary   |   18 |         2 | Edward      |         18 |
|    2 | Edward |   18 |         1 | Mary        |         18 |
|    3 | Jen    |   22 |      NULL | NULL        |       NULL |
+------+--------+------+-----------+-------------+------------+

以下是 SQLFiddle 演示版 这是 SQLFiddle 演示(有超过两个年龄相同的人


在php方面,归结为

$sql = "INSERT INTO match_pairs (ID, Name, Age, PartnerID, PartnerName, PartnerAge)
        SELECT m1.id, m1.name, m1.age,
               m2.id partnerid, m2.name partnername, m2.age partnerage
          FROM `match` m1 LEFT JOIN `match` m2
            ON m1.age = m2.age AND m1.id <> m2.id
         ORDER BY m1.id";

$result = mysql_query($sql);
if (!$result) {
    die('Invalid query: ' . mysql_error()); //TODO better error handling
}