I have a query:
SELECT * FROM match ORDER BY id ASC
The results will have these:
ID Name Age 1 Mary 18 2 Edward 18 3 Jen 22
I want to pair Mary and Edward because they have the same age: The expected result will be:
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
I want to insert the pair two times in a row with corresponding pair.
Here is my code:
$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++;
}
}
Any other suggestions or codes to make it easy?
If I understand correctly you can do it all with one statement
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 is 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 | +------+--------+------+-----------+-------------+------------+
Here is SQLFiddle demo
Here is SQLFiddle demo (with more than two persons with the same age)
On php side it boils down to
$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
}