开发者

mysql fastest 2 table query

Situation: 2 tables, the first (Persons) storing person names and some other data, and the second (Phones) storing their phone numbers. There can be multiple phone numbers per person (thats why I am using separate tables in the first place).

Goal: Select everything so that in the end I'd have a php array like this:

array
(
'0' => array
       (
        'name' => 'John Smith'
        // other values from table Persons...
        'Phones' => array('0' => '12345', '1' => '324343') // from Phones table

        ),
'1' => array
       (
        'name' => 'Adam Smith'
        // other values from table Persons...
        'Phones' => array('0' => '645646', '1' => '304957389', '2' => '9435798') // from Phones table

        )
);

ETC.

Phones.pe开发者_StackOverflow中文版rson_id = Persons.id

What would be the fastest way to do this? Fastest in a sense of program execution time, not the coding time. I could do simple JOIN but in this case I'd get many duplicate rows, i.e. for each phone I get all the data of the same person again and again in each row if you see what I mean. So I need to work on the array in PHP side. Maybe there's a better way?


One query. Check for typos:

$return = array();
$query = "SELECT pe.id, pe.name, ph.phone FROM Persons pe INNER JOIN phones ph ON pe.id = ph.person_id ";
$results = mysql_query($query);
if($results && mysql_num_rows($results)) {
    while($row = mysql_fetch_assoc($results)) {
        if(!$return[$row['id']]) {
          $return[$row['id']] = array('name' => $row['name'], 'Phones' => array());
        } 
        array_push($return[$row['id']]['Phones'], $row['phone']);
    }
}         
return $return;


Get the person first, and then query for each of the phone numbers.

$return = array();
$query = "SELECT `id`, `name` FROM `Persons`";
$person_results = mysql_query($query);
if($person_results && mysql_num_rows($person_results)) {
  while($person_row = mysql_fetch_assoc($person_results)) {
    $person = array();
    $person['name'] = $person_row['name'];
    $person['phone'] = array();
    $query = "SELECT `number` FROM `Phones` WHERE `person_id` = '{$person_row['id']}'";
    $phone_results = mysql_query($query);
    if($phone_results && mysql_num_rows($phone_results)) {
      while($phone_row = mysql_fetch_assoc($phone_results)) {
        array_push($person['phone'], $phone_row['number']);
      }
    }
  }
}
return $return;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜