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 に答える