1

您将在下面找到我的代码,它不是全部,而是显示了重要的内容。我有一些自定义函数只是用来说明的。我的代码所做的是搜索 MySQL 表并根据当前会话用户 ID 显示所有结果。然后我遍历这些结果,并为每个结果搜索另一个表。这工作得很好,但我只是想看看是否有更好的方法来做到这一点,而不必循环和搜索每个结果行的表

<?php
$table_sql = "SELECT * FROM participation WHERE shop_id = '{$session->user_id}'";
$result = $database->query($table_sql);
$participation = array();
while ($row = $database->fetch_array($result)) {
        $participation[] = array (
                'shop_id'               => $row['shop_id'],
                'qpon_id'           => $row['qpon_id'],
                'distributor_id'        => $row['distributor_id']
        );
}
$qpons = array();
if (isset ($participation)) {
        if (!empty ($participation)) {
                foreach ($participation as $qpon) {
                        $table_sql = "SELECT * FROM qpons WHERE id = '{$qpon['qpon_id']}'";
                        $result = $database->query($table_sql);

                        while ($row = $database->fetch_array($result)) {
                                $qpons[] = array (
                                        'id'                    => $row['id'],
                                        'service'       => $row['service'],
                                        'start_date'    => $row['start_date'],
                                        'end_date'      => $row['end_date']
                                );
                        }
                }
        }
}


if (isset ($qpons)) {
if (!empty ($qpons)) {
foreach ($qpons as $value) {

echo '<tr>';
echo '<td>' . $value['service'] . '</td>';
echo '<td>' . $value['start_date'] . '</td>';
echo '<td>' . $value['end_date'] . '</td>';
echo '<td>' . $value['id'] . '</td>';
echo '<td class="action_icon"><a href="admin-edit.php?id=' . $value['id'] . '"><img src="images/icons/view.png" alt="View"></a></td>';
echo '</tr>';

}

} else {
echo '<tr>';
echo '<td>No Results Found!</td>';
echo '<td></td>';
echo '<td></td>';
echo '<td></td>';
echo '<td></td>';
echo '<td></td>';
echo '<td></td>';
echo '</tr>';
}

}
?>
4

1 回答 1

0

将所有这些放入带有JOIN子句的单个查询中会明显更快。

<?php
$table_sql = "SELECT q.* 
              FROM participation AS p
                  INNER JOIN qpons AS q ON p.qpon_id = q.id
              WHERE shop_id = '{$session->user_id}'";
while ($row = $database->fetch_array($result)) {
    $qpons[] = array (
        'id'                    => $row['id'],
        'service'       => $row['service'],
        'start_date'    => $row['start_date'],
        'end_date'      => $row['end_date']
    );
}
于 2012-11-22T13:47:25.727 回答