获取内部mysql_query的结果,而获取mysql_fetch_array的结果


Get result of mysql_query inside while of mysql_fetch_array

我正在使用下面这样的代码,通过匹配第一个表的id来从第二个表中获取数据。代码运行良好,但我知道它会降低性能,我是一个新手。请帮我用一种简单正确的方法做同样的事情。

<?php
$result1 = mysql_query("SELECT * FROM table1 ") or die(mysql_error());
while($row1 = mysql_fetch_array( $result1 ))
{
$tab1_id = $row1['tab1_id'];
echo $row['tab1_col1'] . "-";
$result2 = mysql_query("SELECT * FROM table2 WHERE tab2_col1='$tab1_id' ") or die(mysql_error());
while( $row2 = mysql_fetch_array( $result2 ))
{
echo $row2['tab2_col2'] . "-";
echo $row2['tab2_col3'] . "</br>";
}
}
?>

您可以连接这两个表,并在单个循环中处理结果。您将需要一些额外的逻辑来检查表1的id是否发生了更改,因为您只想在有不同的id时输出此值:

<?php
// Join the tables and make sure to order by the id of table1.
$result1 = mysql_query("
  SELECT
    *
  FROM 
    table1 t1
    LEFT JOIN table2 t2 ON t2.col1 = t1.id
  ORDER BY
    t1.id") or die(mysql_error());
// A variable to remember the previous id on each iteration.
$previous_tab1_id = null;
while($row = mysql_fetch_array( $result1 ))
{
  $tab1_id = $row['tab1_id'];
  // Only output the 'header' if there is a different id for table1.
  if ($tab1_id !== $previous_tab1_id)
  {
    $previous_tab1_id = $tab1_id;
    echo $row['tab1_col1'] . "-";
  }
  // Only output details if there are details. There will still be a record
  // for table1 if there are no details in table2, because of the LEFT JOIN
  // If you don't want that, you can use INNER JOIN instead, and you won't need
  // the 'if' below.
  if ($row['tab2_col1'] !== null) {
    echo $row['tab2_col2'] . "-";
    echo $row['tab2_col3'] . "</br>";
  }
}

不需要2个while循环,您可以连接2个表,然后迭代结果。

如果您不确定什么是join,请查看此处:https://dev.mysql.com/doc/refman/5.1/de/join.html

这里还有一个使用join编写的相当简单的查询:join query Example

您可以使用它。具有两个表的一个关系:

 <?php
    $result1 = mysql_query("SELECT tab2_col2, tab2_col3 FROM table1, table2 where tab2_col1 = tab1_id ") or die(mysql_error());
    while($row1 = mysql_fetch_array( $result1 ),)
    {
        echo $row2['tab2_col2'] . "-";
        echo $row2['tab2_col3'] . "</br>";
    }
    ?>

正如Sushant所说,最好使用一个JOIN或更简单的东西:

 SELECT * FROM table1, table2 WHERE `table1`.`id` = `table2`.`id