我使用类似下面的代码通过匹配第一个表的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>";
}
}
?>
答案 0 :(得分:1)
您可以加入这两个表并在单个循环中处理结果。你需要一些额外的逻辑来检查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>";
}
}
答案 1 :(得分:0)
而不是有2个while循环,你可以做的是加入2个表然后迭代结果。
如果您不确定此处的加入方式是什么:https://dev.mysql.com/doc/refman/5.1/de/join.html
此处还有一个使用join编写的相当简单的查询:Join Query Example
答案 2 :(得分:0)
你可以用它。与两个表的一个关系:
<?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>";
}
?>
答案 3 :(得分:0)
像Sushant所说,最好使用一个JOIN或更简单的东西:
SELECT * FROM table1, table2 WHERE `table1`.`id` = `table2`.`id