0

我之前获得了有关如何将多个表连接在一起以使此导航列表工作的帮助,正如您所看到的,我已经这样做了,但是现在我正在尝试在列表中输出导航,但是它重复了顶部和底部基于这些类别中有多少产品的类别:这是显示我的表格设置的上一个链接:

使用外键 id 连接 2 个表

这是我试图正确回显导航的代码。

try
{ 
    $result = $pdo->query('SELECT product.*, bottom_category.bottom_name, top_category.top_name
                            FROM product
                            INNER JOIN bottom_category ON bottom_category.id = product.bottom_category_id 
                            INNER JOIN top_category ON top_category.id = bottom_category.top_category_id
                            ORDER BY top_category.id,bottom_category.id');
} // end try
catch (PDOException $e) 
{ 
    echo 'There was a error fetching the products.' . $e->getMessage();
    exit(); 
} // end catch

$products = array();

foreach ($result as $row)
{
$products[] = array('top_name' => $row['top_name'], 
              'bottom_name' => $row['bottom_name']);
}

?>

<div class="sidebar">
    <h4 class="sidebar-header">Select Products</h4>
    <form class="nav-search-form">
        <input type="search" name="search" placeholder="Search products">
    </form>
    <nav class="sidebar-links"> 
        <ul>
            <li><a id="red" href="/semtronics/index.php">New Products</a></li>
            <?php
            foreach ($products as $product):
            ?>
            <li><a href="#"><?php echo htmlspecialchars($product['top_name']);?></a>

                <ul>
                    <li><a href=""><?php echo htmlspecialchars($product['bottom_name']);?></a></li>
                </ul>
            </li>
            <?php endforeach; ?>        
        </ul>
    </nav>
</div><!-- sidebar -->

现在一切正常,唯一的问题是它是根据链接到该类别的产品数量来复制导航列表。

4

1 回答 1

0

我认为您需要另一种解决方案来完成此任务。您在这里不需要产品

查询你需要的是:

select bottom_category.name as bottom_name, top_category.name as top_name
from bottom_category
inner join top_category on top_category.id = bottom_category.top_category_id
order by top_category.id, bottom_category.id

我在想您需要product代码中的表中的某些内容,但如果不需要,请使用上面的 SQL 查询。

或者您需要产品表中的数据?

如果你需要,product你可以运行

select bottom_category.name as bottom_name, top_category.name as top_name
from product
inner join bottom_category on bottom_category.id = product.bottom_category_id 
inner join top_category on top_category.id = bottom_category.top_category_id
group by product.bottom_category_id
order by top_category.id, bottom_category.id

但请注意,您不知道在这种情况下将使用 product 中的哪一行

于 2013-08-09T17:30:43.310 回答