1

私は 2 つのカテゴリ システムを持っています。基本的には、top_category と bottom_category の 2 つのテーブルが必要です。SQL クエリを使用してすべての製品を一覧表示するサイドバーを作成しました。top_category と bottom_category のデータを 1 つの SQL クエリで取得し、bottom_category を top_category の外部キー ID でソートして、リストでそれらをループすると、正しいネストになってしまう方法はありますか?

これが私のテーブルです。

CREATE TABLE top_category (
  id INT PRIMARY KEY,
  NAME VARCHAR(100) 
);

CREATE TABLE bottom_category (
  id INT PRIMARY KEY,
  NAME VARCHAR(100) ,
  top_category_id INT REFERENCES top_category
);

そして、ここに私の製品テーブルがあるので、bottom_category リンクをクリックすると、bottom_category_id にリンクされた製品をリストする必要があります。

create table product (
  id int primary key,
  name varchar(100) ,
  bottom_category_id int references bottom_category
);
4

2 に答える 2

0
select p.*,
      bc.name bc_name,
      tc.name tc_name
from product p
left join bottom_category bc on p.bottom_category_id=bc.id
left join top_category tc on bc.top_category_id=tc.id
order by tc.id,bc.id
于 2013-08-09T16:01:09.730 に答える
0

次のようなものを書くことができます

SELECT product.*, bottom_category.name, top_category.name
FROM product
LEFT JOIN bottom_category ON bottom_category.id = product.bottom_category_id 
LEFT JOIN top_category ON top_category.id = bottom_category.top_category_id
ORDER BY top_category.id,bottom_category.id

ただし、非常に大きなテーブルがある場合は、第 3 正規形を忘れて、製品テーブルにカテゴリの名前を追加してください。ただし、カテゴリを含む非常に大きなテーブルがある場合に限ります。

UPD 追加ORDER BY

于 2013-08-09T16:00:29.453 に答える