查询优化/数据检索

i have a query which pulls some data from table A and table B. there's a one to many relationship between the two where table A is the one. i'm not super good with mysql, and was wondering if i could perform this query better? the loop to fetch the data was the only way i could figure out how to arrange it all for display purposes since the query duplicates the info in table A for every unique row in table B. was wondering if anyone could show me a better way?

$sql = "
  SELECT core.`id` AS attribute_id, core.`gender` as attribute_gender , core.`order` as attribute_order, core.`name` as attribute_name, coreval.`id` AS value_id, coreval.`value` as value_name
  FROM  `core_attributes` core
  LEFT OUTER JOIN  `core_attribute_values` coreval 
  ON core.id = coreval.attribute_id
  WHERE core.active = 1 
  ORDER BY attribute_order
";

try {
  $stmt = $dbh->prepare($sql);
  $stmt->execute(array(':agency_id' => $agency_id));

  $result = array();

  while($row = $stmt->fetch()) {
    $result[$row['attribute_id']]['attribute_id'] = $row['attribute_id'];
    $result[$row['attribute_id']]['attribute_gender'] = $row['attribute_gender'];
    $result[$row['attribute_id']]['attribute_order'] = $row['attribute_order'];
    $result[$row['attribute_id']]['attribute_name'] = $row['attribute_name'];
    $result[$row['attribute_id']]['values'][$row['value_id']] = $row['value_name'];
  }
  return $result;
}

edit: removed a part of the query unrelated to my question

Use mySQL's

EXPLAIN SELECT ...

statement to learn, how mySQL executes your statement. From there, go ahead and modify it.

the while loop can be managed with a further foreach loop, making it a little simpler.

while($row = $stmt->fetch()) {

    // Set $id for each iteration of the while loop
    $id = $row['attribute_id'];

    foreach ($row as $key => $value) {

        // Set $result to the corresponding key => value pairs
        $result[$id][$key] = $value;

    }
}

Your mySQL statement looks ok to me!