【问题标题】:Get result of mysql_query inside while of mysql_fetch_array在 mysql_fetch_array 中获取 mysql_query 的结果
【发布时间】:2013-12-08 11:09:41
【问题描述】:

我正在使用类似下面的代码通过匹配第一个表的 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>";
}

}
?>

【问题讨论】:

  • 这是正常的取数据方式,没有错
  • 对不起,我误解了这个问题。根据您要对数据执行的操作,这就是执行此操作的方法 - 就像 Pekka 所说的那样。
  • @Pekka웃,我们没有其他好方法来处理这个问题吗?
  • @kingkero 感谢您的回复,但这不会降低性能吗?
  • 啊,现在的代码看起来不一样了。

标签: php mysql arrays while-loop fetch


【解决方案1】:

就像 Sushant 所说,最好使用一个 JOIN 或更简单的类似的东西:

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

【讨论】:

  • 我也试过了,效果也很好。做同样的事情的简单直接的方法。
【解决方案2】:

您可以连接两个表并在一个循环中处理结果。您将需要一些额外的逻辑来检查 table1 的 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>";
  }
}

【讨论】:

    【解决方案3】:

    你可以使用它。两个表的一个关系:

     <?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>";
    
        }
        ?>
    

    【讨论】:

    • 这个方法也很好用,简单直接的方式来获得结果
    【解决方案4】:

    您可以做的是加入 2 个表,然后迭代结果,而不是 2 个 while 循环。

    如果您不确定加入是什么,请看这里:https://dev.mysql.com/doc/refman/5.1/de/join.html

    这里还有一个使用连接编写的相当简单的查询:Join Query Example

    【讨论】:

      猜你喜欢
      • 2014-01-02
      • 1970-01-01
      • 2012-11-04
      • 2013-06-19
      • 2014-04-09
      • 2020-09-28
      • 2016-07-30
      • 1970-01-01
      相关资源
      最近更新 更多